Igor Igor - 1 month ago 5
Android Question

Getting Called From Wrong Thread Exception

I have activity which creates Thread to communicate with server. This thread every few seconds receives a String. I would like to add this String to list and display in activity (in ListView) but I'm getting CalledFromWrongThreadException when trying to do that.

class MyActivity() extends AppCompatActivity {

ArrayList<String> list;
ArrayAdapter<String> adapter;

public MyActivity(){

...

setContentView(R.layout.main);

list = new ArrayList<>();
ListView myList = (ListView) findViewById(R.id.my_list);
adapter = new ArrayAdapter<>(this, R.layout.list_element, list);

myList.setAdapter(adapter);

Thread thread = new Thread(new Runnable(){
@Override
public void run(){

while(true){
String dataFromServer = networkManager.receiveData();
list.add(dataFromServer);
adapter.notifyDataSetChanged();
}
}
});
}
}


How can I solve this?

Answer

Switch back to the UI thread before you manipulate the list.

      list.post (new Runnable()
      {
        @Override public void run() 
        {
          String dataFromServer = networkManager.receiveData();
          list.add(dataFromServer);
          adapter.notifyDataSetChanged();
        }
      });