Reputation: 5164
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 ?
Upvotes: 4
Views: 4119
Reputation: 34704
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.
Upvotes: 6
Reputation: 128428
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.
Upvotes: 4