AsyncTask and setAdapter in onCreate methods

I am doing heavy network tasks - loading images (preview) - Since my main user interface was not blocked, he did it in AsyncTask, I want to put them in the GridView, but I installed the adapter before AsyncTask is complete. Some code will be more useful

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, Logcat shows that everything was loaded, but nothing on my screen. I tried to make 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?

+4
source share
3 answers

AsyncTask has a useful method that can be implemented with the name onPostExecute() . He called from the original user interface thread after the task was completed. You can use it to install the adapter from the correct stream.

+6
source

AsyncTask has 3 main 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 images are already loaded inside the doInBackground() method.

+4
source

For convenient asynchronous loading of images and installing them in Views, you can use the very useful and simple Picasso library:

 Picasso.with(context) .load(url) .placeholder(R.drawable.user_placeholder) .error(R.drawable.user_placeholder_error) .into(imageView); 

If you are using Android Studio and gradle, just add this to the gradle application level file:

 compile 'com.squareup.picasso:picasso:2.5.2' 

The latest version is available on Github .

0
source

All Articles