Search code examples
androidlistviewandroid-listview

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?


Solution

  • 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();
            }
        });
    }