views:

163

answers:

2

Hi,

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

+1  A: 

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

Erich Douglass
You should be creating a new Runnable, not a new Thread.
Romain Guy
Both didn't work because now my ProgressDialog won't appear anymore, that was the main reason to put the method in a separate thread.
Mats Hofman
where is the code for progressDialog.show() ?
Alex Volovoy
the progressDialog is a field and filled in directly above it (question edited)
Mats Hofman
+1  A: 

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();
Mats Hofman