Weak Reference in Java and Android

Last week i have trouble in Picasso(http://square.github.io/picasso/), when i want to :

    Picasso.with(context).load(url).into(new Target(){
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {

    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {

    }
};

But unfortunately when i run this code, onBitmapLoaded is not called. Why ? after read this http://stackoverflow.com/questions/24180805/onbitmaploaded-of-target-object-not-called-on-first-load i know the problem because Target object is weak because clear on JVM(http://en.wikipedia.org/wiki/Java_virtual_machine) so what is the solution ?

  1. You can make the target as Class attribute (http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html), so you don’t make the target as inline object.
  2. Or you can use WeakReference (http://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html) class, after reading https://weblogs.java.net/blog/2006/05/04/understanding-weak-references what i do is :

    WeakReference ref = new WeakReference(target);

And after that my whole code will be :

Target target = new Target(){
    @Override
    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
        //put the code here
    }

    @Override
    public void onBitmapFailed(Drawable errorDrawable) {

    }

    @Override
    public void onPrepareLoad(Drawable placeHolderDrawable) {

    }
};
WeakReference<Target> ref = new WeakReference<Target>(target);
Picasso.with(context).load(url).into(ref.get());
 
5
Kudos
 
5
Kudos

Now read this

MultiPart Upload File using Retrofit

We can upload file to server using several technique. But this one i want to demonstrate how to upload file using Retrofit. To upload file using retrofit, you need to wrap your file to TypedFile. How to do it ? Basically TypeFile is... Continue →