2011-12-29 50 views
22

我創建一個線程來更新我的數據,並嘗試在我的ListView上執行notifyDataSetChanged如何在線程中使用notifyDataSetChanged()

private class ReceiverThread extends Thread { 

@Override 
public void run() { 
    //up-to-date 
    mAdapter.notifyDataSetChanged(); 
} 

錯誤發生在線路:

mAdapter.notifyDataSetChanged(); 

錯誤

12-29 16:44:39.946:E/AndroidRuntime(9026):android.view。 ViewRoot $ CalledFromWrongThreadException:只有創建視圖層次結構的原始線程才能觸及其視圖。

我應該如何修改它?

回答

41

使用runOnUiThread()方法來執行從非UI線程的UI動作。

private class ReceiverThread extends Thread { 
@Override 
public void run() { 
Activity_name.this.runOnUiThread(new Runnable() { 

     @Override 
     public void run() { 
      mAdapter.notifyDataSetChanged(); 
     } 
    }); 
} 
+0

謝謝......它完全適用於我 – 2014-05-28 10:08:45

+0

Thanks.Very good ... – 2014-07-20 10:09:22

4

您無法從其他線程訪問UI線程。您必須使用處理程序來執行此操作。您可以將消息發送到您的運行方法中的處理程序並更新UI(調用mAdapter.notifyDataSetChanged())內部處理程序。

5

您無法觸及其他線程的UI視圖。對於您的問題,您可以使用AsyncTask,runOnUiThread處理程序

萬事如意

1

access the UI thread from other threads

Activity.runOnUiThread(Runnable接口)

View.post(Runnable接口)

View.postDelayed(Runnable接口,長)

我的方法當我使用其他線程工作:

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

順便說一句notifyDatasetChanged()方法鉤AbsListView的DataSetObservable類對象是由通過設置回調Adapter.registerDataSetObserver(DataSetObserver)涉及AbsListView.setAdaptert(適配器)方法首先設置;