Vinit Shandilya
Vinit Shandilya

Reputation: 1643

Update a ListView from different threads

Sorry if the question seems silly.. I'm still learning Java. I just wanted to know, is it possible to update my ListView in MainActivity class from different threads? I tried passing my activity context in thread constructor and get instance of ListView like this:

ListView lv = (ListView)parentActivity.findViewById(R.id.listViewInXml);

Then I updated this ListView as per my requirement after the thread execution is complete. But the problem is, each thread gets different instance on the ListView and each one of them adds item to the 0 index (it assumes the ListView is newly created at the start of each thread). I want that each thread completes its execution and add the result on by one in the ListView of MainActivity class. Any suggestions please? Here is a skeleton of what I'm trying to do:

    MainActivity extends Activity {

onCreate (bundle icicle) {

   getReferencetoListView();
   int userId = 1;
   while (true) {  
      // Execute a thread with userId
     // Each thread takes some time to complete execution
     userId++
     }
  }
}

Thread (userId =1)

Thread (userId =2)

Thread (userId =3) 
.
.
.
and so on..

Thanks for your help!

Upvotes: 0

Views: 121

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006819

I just wanted to know, is it possible to update my ListView in MainActivity class from different threads?

No. You cannot modify the UI from a background thread outside of a few select cases (e.g., ProgressBar). This is covered in the documentation.

Upvotes: 1

Related Questions