Muddz Muddz - 3 months ago 41
Android Question

setBackground() in onActivityResult is never called

In my app the user can pick a image from the gallery and set it to the background of a

RelativeLayout
. But the image is never immediately set as to the background in my onActivityResult() method as supposed to when I load the bitmap of the choosen picture with picasso to my view.

Here is a screenrecord video of the problem: https://www.youtube.com/watch?v=jABnheTV0IU

But when this method inside my RecyclerView Adapter is called the image is set as background to the RelativeLayout immediately:

@Override
public void onClick(final View v) {

int position = getLayoutPosition();
String path = PreferenceManager.getDefaultSharedPreferences(context).getString(App.IMAGE_URI,"");

/*
This put the current selected image from the gallery as background
*/
if (position == 0 && !path.isEmpty()) {

Picasso.with(context).load(path).centerCrop().resize(view.getWidth(), view.getHeight()).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
view.setBackground(new BitmapDrawable(bitmap));
}

@Override
public void onBitmapFailed(Drawable errorDrawable) {

}

@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {

}
});


the onActivityResult in my MainActivity class.

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {


if (resultCode == RESULT_OK && requestCode == 1 && data.getData() !=null) {

PreferenceManager.getDefaultSharedPreferences(this).edit().putString(App.IMAGE_URI, data.getData().toString()).apply();

Picasso.with(this).load(data.getData()).centerCrop().resize(width, height).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

//this is never called or dosn't work
relativeLayout.setBackground(new BitmapDrawable(bitmap));


}

@Override
public void onBitmapFailed(Drawable errorDrawable) {

}

@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {

}
});

}
}

Answer

According this Picasso only keeps a weak reference to the Target object. Which mean that you need to make hard reference to it somewhere. Make Target as MainActivity class memeber. So call to load will look like so:

//Create Target right before it's needed
mTarget = new Target() {/*same as in your question*/};
Picasso.with(this).load(data.getData()).centerCrop().resize(width, height).into(mTarget);

Or you could declarate following inner class

private static ViewTarget implement Target {
    private View mView;
    public ViewTarget(View view) {
        mView = view;
    }

    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        mView.setBackground(new BitmapDrawable(bitmap));
    }
};

And use it like so:

mTarget = new ViewTarget(relativeLayout);
Picasso.with(this).load(data.getData()).centerCrop().resize(width, height).into(mTarget);