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?
notifyDataSetChanged. Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
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.
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.
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.
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(); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With