How to use notifyDataSetChanged() in thread
Asked Answered
S

5

29

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?

Subgenus answered 29/12, 2011 at 8:50 Comment(0)
S
49

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();
        }
    });
}
Spinose answered 29/12, 2011 at 9:16 Comment(0)
B
9

You can not touch the views of the UI from other thread. For your problem you can use either AsyncTask, runOnUiThread or handler.

All The Best

Backgammon answered 29/12, 2011 at 9:12 Comment(0)
W
4

You cant access UI thread from other thread.You have to use handler to perform this.You can send message to handler inside your run method and update UI (call mAdapter.notifyDataSetChanged()) inside handler.

Whenas answered 29/12, 2011 at 8:55 Comment(0)
P
1

access the UI thread from other threads

Activity.runOnUiThread(Runnable)

View.post(Runnable)

View.postDelayed(Runnable, long)

my approach whe i use other Threads for work:

private AbsListView _boundedView;
private BasicAdapter _syncAdapter;

 /** bind view to adapter */
public void bindViewToSearchAdapter(AbsListView view) {
    _boundedView = view;
    _boundedView.setAdapter(_syncAdapter);
}

/** update view on UI Thread */
public void updateBoundedView() {
    if(_boundedView!=null) {
        _boundedView.post(new Runnable() {
            @Override
            public void run() {
                if (_syncAdapter != null) {
                    _syncAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}

btw notifyDatasetChanged() method hooks to DataSetObservable class object of AbsListView which is set first by involving AbsListView.setAdaptert(Adapter) method by setting callback to Adapter.registerDataSetObserver(DataSetObserver);

Pattipattie answered 2/7, 2015 at 0:3 Comment(0)
K
0

You can write in this way also.

  new Handler().postDelayed(new Runnable() {
                public void run() {
                    test();
                }
            }, 100);

private void test() {
    this.notifyDataSetChanged();
}

just test it.

Keilakeily answered 26/2, 2020 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.