简体   繁体   English

listView更新不适用于静态变量

[英]listView update doesn't work with static variable

I've got a ListView with a custom adapter. 我有一个带有自定义适配器的ListView。 I want to update the data of the ListView. 我想更新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: 我现在的问题是,当我想在UI线程外部使用以下函数调用此函数时,该函数不在OffersActivity中,它不起作用:

@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. 适配器是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. 您不能从原始UI线程以外的任何线程运行notifyDataSetChanged() 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. 首先,您的方法应该是名称updateData而不是addData因为它不会添加任何内容,只能用新的数据替换旧数据。

Then try (assuming your handleDelivery method is in your Activity): 然后尝试(假设您的handleDelivery方法在您的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));
                        }
                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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