Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AsyncTask and setAdapter in onCreate methods

I am doing some heavy network tasks - downloading pictures (previews) - For my main UI to not be blocked it did that in an AsyncTask, I want to put them in a GridView but I set the adapter before the AsyncTask finishes. Some code will be more helpfull

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.gridview);
            new LoadAllPictures().execute();
            GridView g = (GridView) findViewById(R.id.gridview);
            g.setAdapter(new ImageAdapter(this));
}

So at the end the Logcat shows that everything had been dowloaded but nothing on my screen. I tried doing the setAdapter part in my AsyncTask but it tells me that: Only the original thread that created a view hierarchy can touch its views.

What should I do ?

like image 809
Spredzy Avatar asked Dec 28 '22 05:12

Spredzy


2 Answers

AsyncTask has a useful method you can implement named onPostExecute(). It's called from the original UI thread after the task has completed. You can use it to set the adapter from the correct thread.

like image 105
kichik Avatar answered Dec 30 '22 19:12

kichik


AsyncTask has 3 basic methods:

protected void onPreExecute()
{
}

protected void onPostExecute(Void unused)   
{
  // displaying images
  // set adapter for listview with downloaded items
}

protected Void doInBackground(Void... params) 
{
     // downloading and time consuming task 
}

so you can write g.setAdapter(new ImageAdapter(this)); inside the onPostExecute(Void unused) method because at this time, the pictures are already downloaded inside the doInBackground() method.

like image 45
Paresh Mayani Avatar answered Dec 30 '22 17:12

Paresh Mayani