Android, ListView IllegalStateException: “The content of the adapter has changed but ListView did not receive a notification”

后端 未结 25 2454
执念已碎
执念已碎 2020-11-22 16:59

What I want to do: run a background thread which calculates ListView contents and update ListView partially, while results are calculated.

W

25条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 17:43

    I was also getting exact same error and using AsyncTask :

    `java.lang.IllegalStateException:` The content of the adapter has changed but ListView  did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131296334, class android.widget.ListView) with Adapter... etc
    

    I solved it by puttingadapter.notifyDataSetChanged(); at the bottom of my UI thread, that is my AsyncTask onPostExecute method. Like this :

     protected void onPostExecute(Void aVoid) {
    
     all my other stuff etc...
        all my other stuff etc...
    
               adapter.notifyDataSetChanged();
    
                    }
    
                });
            }
    

    Now my app works.

    EDIT : In fact, my app still crashed about every 1 in 10 times, giving the same error.

    Eventually I came across runOnUiThread on a previous post, which I thought could be useful. So I put it in my doInBackground method, like this :

    @Override
    protected Void doInBackground(Void... voids) {
    
        runOnUiThread(new Runnable() {
                          public void run() { etc... etc...
    

    And I removed the adapter.notifyDataSetChanged(); method. Now, my app never crashes.

提交回复
热议问题