Question

I have a problem with my ListActivity, i use a thread to show a ProgressDialog where get a list of all installed applications. I turn it into a list adapter and than i want to set the listadapter of the activity but i can't do that from the thread.

I get the following error: ERROR/AndroidRuntime(14429): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Loading...");
progressDialog.show();
new Thread() {
        public void run() {
              showList(); // the method where i get all the apps and have the setListAdapter(); method
              progressDialog.dismiss();
        }
}.start();

How do I get it so I can use the setListAdapter from inside my thread

Was it helpful?

Solution

I solved it, by using a Handler i managed to get the setListAdapter out of the Thread and still waiting for the Thread to execute the method.

final Handler h = new Handler(){
    public void handleMessage(Message msg) {
        setListAdapter(appsAdapter);
    }           
};

new Thread() {
    public void run() {
        showList();
        progressDialog.dismiss();
        h.sendEmptyMessage(0);
    }
}.start();

OTHER TIPS

The easiest way to do this is to use the Activity's runOnUiThread method:

runOnUiThread(new Runnable() {
    public void run() {
        showList();
        progressDialog.dismiss();
    }
});

Edit: Changed Thread to Runnable

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top