1
votes

I'm developing an Android application and I'm using Eclipse as IDE and my database is MySQL. I have the follow problem. When I try to take datas from the database through the AsynTask I have the error that I show below.

android.view.ViewRootImpl$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy 
can touch its views

Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);
   asyn=new MyAsyncTask();

   tvtexto=(TextView)findViewById(R.id.tvtextoMa);
   context = getApplicationContext();
   eventos = new ArrayList<Eventos>();
   eventosAdapter = new EventosAdapter(context, R.layout.filae, eventos);
   eventos=new ArrayList<Eventos>();
   asyn.execute();
   listView = (ListView)findViewById(R.id.ListView01Ma);
}

AsyncTask:

public class MyAsyncTask extends AsyncTask<Void, Void, Void> 
{
   @Override
   protected Void doInBackground(Void... arg0) 
   {
      eventos=(ArrayList<Eventos>) BDEventos.getDatosEventos();
      for(Eventos n:eventos){
         eventosAdapter.add(n);
      }
      eventosAdapter.notifyDataSetChanged();
      listView.setAdapter(eventosAdapter);
      return null;
   }
}
1
You will find a lot of answers to your problem searching for '[android] CalledFromWrongThreadException'.Günter Zöchbauer

1 Answers

0
votes

Updating ui from background thread is not possible. `doInbackground is invoked on the background thread. Ui should be updated on the ui thread.

Get your data form data base in doInbackground return result and update ui accordingly in onPostExecute.

eventosAdapter.notifyDataSetChanged();
listView.setAdapter(eventosAdapter);

SHould be in onPostExecute