Nugget Post: Android threads and array adapters

An important point of note when using array adapters in android is that the notifyDataSetChanged method can only be called in the main UI thread. So when developing multithread android apps, it’s important that the method is called within a runOnUiThread or similar. The notifyDataSetChanged is used to inform an array adapter that it’s data source has been updated, so it should refresh it’s linked UI element (usually a listview or similar). So an android developer should have something like this in an android fragment:

 

getActivity().runOnUiThread(new Runnable() {

public void run() {
adapter.add(argument.toString());
}
});

 

Note how in the above example I am using the add method, whose implementation includes the notifyDataSetChanged method, and hence must be included in the runOnUiThread method.