brian
brian

Reputation: 6922

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?

Upvotes: 29

Views: 28625

Answers (5)

Gyan Swaroop Awasthi
Gyan Swaroop Awasthi

Reputation: 699

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.

Upvotes: 0

ceph3us
ceph3us

Reputation: 7484

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);

Upvotes: 1

Richa
Richa

Reputation: 3193

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

Upvotes: 9

Lalit Poptani
Lalit Poptani

Reputation: 67296

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

Upvotes: 50

Ramindu Weeraman
Ramindu Weeraman

Reputation: 354

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.

Upvotes: 4

Related Questions