简体   繁体   English

如何在另一个线程上的回调内的ArrayAdapter中notifyDataSetChanged? -安卓

[英]How do I notifyDataSetChanged in ArrayAdapter inside a callback on a different thread? - Android

I am making a network call, then once the network call is done retrieving the information, I would like to call notifyDataSetChanged. 我正在进行网络通话,然后在完成网络通话检索信息后,我想致电notifyDataSetChanged。 This works if it's all on the same thread, but how would I go about updating the list if the update is happening in another thread? 如果所有线程都在同一线程上,则此方法有效,但是如果更新发生在另一个线程中,我将如何更新列表?

** **

It will throw this error: 它将抛出此错误:

android.view.ViewRootImpl$CalledFromWrongThreadException: 
Only the original thread that created a view hierarchy can touch its views.

You can use AsyncTask to perform your networking operation on a separate thread. 您可以使用AsyncTask在单独的线程上执行网络操作。 You start the AsyncTask from your UI thread and the task itself will run on a separate thread. 您从UI线程启动AsyncTask,任务本身将在单独的线程上运行。 When the AsyncTask is done, AsyncTask's onPostExecute method will run on the UI thread again from which you can call the notifyDataSetChanged() method. 完成AsyncTask后,AsyncTask的onPostExecute方法将再次在UI线程上运行,您可以从该UI线程调用notifyDataSetChanged()方法。

Here's some useful info on AsyncTask in the Android developer docs 这是Android开发人员文档中有关AsyncTask的一些有用信息

You should use a handler. 您应该使用处理程序。 Declare your adapter like an atribute of the class (outside any method). 像类的属性一样声明适配器(在任何方法之外)。 And use this code in your activity: 并在您的活动中使用以下代码:

public Handler updateAdapter = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg)
    {
        //Update code
    }
});

And this one in your thread (to call the handler): 而这在您的线程中(调用处理程序):

updateCode.sendEmptyMessage(0);

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

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