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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With