我们可以在doInBackground()中运行runUnUhThread吗?

时间:2013-06-12 15:15:21

标签: java android

@
Override
protected Boolean doInBackground(final String...params) {

    runOnUiThread(new Runnable() {
            public void run() {

问题是当AysncTask被执行并且onPostExecute()被调用时(其中mAllResultsAdapter.notifyDataSetChanged();被调用),the Adapter has not bound to ListView yet。我得到以下例外。

  

java.lang.IllegalStateException:适配器的内容有   已更改,但ListView未收到通知。确保   您的适配器的内容不会从后台线程修改,但是   仅来自UI线程。 [在ListView(2131034153,类   android.widget.ListView)with Adapter(class   COM .... tracebuzz.allresults.AllResultsAdapter)]

问题是在后台线程中更改了绑定到ArrayList Adapter的{​​{1}}。

The content of the adapter has changed but ListView did not receive a notification - With AsyncTask

上面的问题是我的确切情况,但我不知道如何应用我的情况,其中有10 ArrayList在后​​地线程中被修改,10 Adapaters需要通知。

4 个答案:

答案 0 :(得分:0)

不要仅在UI线程中更改后台线程中的适配器数据。后台线程应该创建一个本地变量列表,并在onPostExecute上,或者通过runOnUiThread,将列表复制到适配器列表并调用notifyDataSetChanged

答案 1 :(得分:0)

只需将notifyDataSetChanged移动到异步任务的onPostExecute方法即可。 doInBackground完成后,此方法在UI线程上运行。这样,您可以在后台下载和更新适配器内容,只需刷新UI线程上的实际视图即可。

答案 2 :(得分:0)

我猜你应该能够在AsyncTask中的ui Thread上运行代码。

如果您无权访问上下文,请使用

new Handler(Looper.getMainLooper()).post(youRunnable);

答案 3 :(得分:0)

我曾经遇到过同样的问题。我尝试了很多东西,包括runOnUiThread,但我认为最好的解决方案是在AsyncTask中创建一个时间ArrayList,以便在doInBackground()中填充它。然后,您可以将所有这些元素刷新到真正的ArrayList中,并在onPostExecute()方法(在UI线程上运行)中通知适配器。

相关问题