Search code examples
androidandroid-asynctaskandroid-sdk-2.1android-gridview

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 ?


Solution

  • 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.