2011-12-29 11 views
22

Creo un hilo para actualizar mis datos y trato de hacer notifyDataSetChanged en mi ListView.Cómo utilizar notifyDataSetChanged() en el hilo

private class ReceiverThread extends Thread { 

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

El error se produce en la línea:

mAdapter.notifyDataSetChanged(); 

Error:

12-29 16: 44: 39.946: E/Android Runtime (9026): android.view. ViewRoot $ CalledFromWrongThreadException: solo el subproceso original que creó una jerarquía de vista puede tocar sus vistas.

¿Cómo debo modificarlo?

Respuesta

41

Uso runOnUiThread() método para ejecutar la acción de interfaz de usuario de un hilo no-UI.

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

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

Gracias ... Funciona perfectamente para mí –

+0

Gracias.Muy bien ... –

4

No puede acceder al subproceso de IU desde otro subproceso. Debe utilizar el manejador para realizar esto. Puede enviar un mensaje al controlador dentro de su método de ejecución y actualizar la IU (llamar a mAdapter.notifyDataSetChanged()) dentro del controlador.

5

No puede tocar las vistas de la IU desde otro hilo. Para su problema, puede usar AsyncTask, runOnUiThread o manipulador.

todo lo mejor

1

access the UI thread from other threads

Activity.runOnUiThread (Ejecutable)

View.post (Ejecutable)

View.postDelayed (Ejecutable, larga)

mi acercamiento cuando uso otros hilos para el trabajo:

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

cierto notifyDatasetChanged() método ganchos a objeto de clase DataSetObservable de AbsListView que se establecen primero mediante la participación de método AbsListView.setAdaptert (adaptador) mediante el establecimiento de devolución de llamada para Adapter.registerDataSetObserver (DataSetObserver);

Cuestiones relacionadas