Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use notifyDataSetChanged() in thread

I create a thread to update my data and try to do notifyDataSetChanged at my ListView.

private class ReceiverThread extends Thread {  @Override public void run() {      //up-to-date     mAdapter.notifyDataSetChanged(); } 

The error occurs at line:

mAdapter.notifyDataSetChanged(); 

Error:

12-29 16:44:39.946: E/AndroidRuntime(9026): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

How should I modify it?

like image 632
brian Avatar asked Dec 29 '11 08:12

brian


People also ask

What is the use of notifyDataSetChanged?

notifyDataSetChanged. Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

How do I notify my adapter?

Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity . Then, notifyDataSetChanged() will work.

What does notifyDataSetChanged do in Recyclerview?

notifyDataSetChanged. Notify any registered observers that the data set has changed. There are two different classes of data change events, item changes and structural changes. Item changes are when a single item has its data updated but no positional changes have occurred.

How does notifyDataSetChanged work on Android?

Suppose your ListView displays some data stored in an ArrayList . After you change the contents of the ArrayList , you need to tell the list that the source of the data had changed and it needs to redraw itself to show the new data. So, that is where notifyDatasetChanged() comes in.


1 Answers

Use runOnUiThread() method to execute the UI action from a Non-UI thread.

private class ReceiverThread extends Thread { @Override public void run() {  Activity_name.this.runOnUiThread(new Runnable() {          @Override         public void run() {              mAdapter.notifyDataSetChanged();         }     }); } 
like image 92
Lalit Poptani Avatar answered Sep 25 '22 03:09

Lalit Poptani