Ayushi bhardwaj Ayushi bhardwaj - 2 months ago 10
Java Question

Loading an Image using Picasso

I'm using

Picasso
to load an
Image
from a
URL
, After I run the application I get to see that "Application may be doing too much work on its main thread". To set the
Image
I'm writing some thing like this :

Picasso.with(ScrollingActivity.this).load(photoUrl).networkPolicy(NetworkPolicy.OFFLINE).into(userProfileImageView, new Callback() {
@Override
public void onSuccess() {

}

@Override
public void onError() {
with(ScrollingActivity.this).load(photoUrl).into(userProfileImageView);
}
});


Now I'm thinking to use
AsyncTask
to set the
Image
into
ImageView
and for that I modified my code to something like :

But now I don't know what to write in
doInBackground
method and
onPostExecute
method.

I used the
AsyncTask
method like this :

class SetImageTask extends AsyncTask<Void, Void, Void>
{

@Override
protected Void doInBackground(Void... voids) {

Picasso.with(ScrollingActivity.this).load(photoUrl).networkPolicy(NetworkPolicy.OFFLINE).into(userProfileImageView, new Callback() {
@Override
public void onSuccess() {

}

@Override
public void onError() {
with(ScrollingActivity.this).load(photoUrl).into(userProfileImageView);
}
});


return null;
}

@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}


But the problem is that I'm setting the Image into the
ImageView
in the
doInBackground
method. So I think that needs to be done in UI thread. Can you please tell me how do I set the
Image
using
AsyncTask

Answer

You don't need to use AsyncTask or and background Thread to load image using Piccaso. Picasso is already optimized. It has its own Asynchronous calls. The problem that you are getting

"Application may be doing too much work on its main thread"

is not due to the Picasso. You can refer this link to see reason behind "Application may be doing too much work on its main thread"