简体   繁体   中英

listView update doesn't work with static variable

I've got a ListView with a custom adapter. I want to update the data of the ListView. To do so I wrote this function inside the adapter:

public void addData(Offer newOffer){
    this.offerList.clear();
    this.offerList.add(newOffer);
    this.notifyDataSetChanged();
}

My problem now is that when I want to invoke this function outside the UI thread with the following function, which is not situated inside OffersActivity, it does not work:

@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    final String message = new String(body, "UTF-8");

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            OffersActivity.offerAdapter.addData(new Offer("test", message));
        }
    });
}

The adapter is a public static variable in OffersActivity. Does anybody has an idea why this is not working?

Bruno

You cannot run notifyDataSetChanged() from any thread other than the original UI thread. Do this

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                OffersActivity.offerAdapter.addData(new Offer("test", message));
            }
        });

    }
});

First of all, your method should be name updateData instead of addData as it doesn't add anything but replace old data with new one.

Then try (assuming your handleDelivery method is in your Activity):

new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
             runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                           // NON static variable
                           OffersActivity.this.offerAdapter.addData(new Offer("test", message));
                        }
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM