Skip to content

Instantly share code, notes, and snippets.

@premithk
Created January 21, 2017 16:02
Show Gist options
  • Save premithk/7311a47e9ee848829ad86595c39878a0 to your computer and use it in GitHub Desktop.
Save premithk/7311a47e9ee848829ad86595c39878a0 to your computer and use it in GitHub Desktop.
A request handler for picasso that will handle firebase storage location like this gs://appname.appspot.com/Images/1.JPG
/**
* Created by premith on 21/01/17.
*/
import android.graphics.BitmapFactory;
import android.util.Log;
import com.google.android.gms.tasks.Tasks;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StreamDownloadTask;
import com.squareup.picasso.Request;
import com.squareup.picasso.RequestHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;
import static com.squareup.picasso.Picasso.LoadedFrom.NETWORK;
public class FireBaseRequestHandler extends RequestHandler {
private static final String SCHEME_FIREBASE_STORAGE = "gs";
@Override
public boolean canHandleRequest(Request data) {
String scheme = data.uri.getScheme();
return (SCHEME_FIREBASE_STORAGE.equals(scheme) );
}
@Override
public Result load(Request request, int networkPolicy) throws IOException {
StorageReference gsReference = FirebaseStorage.getInstance().getReferenceFromUrl(request.uri.toString());
StreamDownloadTask mStreamTask;
InputStream inputStream ;
mStreamTask = gsReference.getStream();
try {
inputStream = Tasks.await(mStreamTask).getStream();
Log.i("FireBaseRequestHandler", "Loaded " + gsReference.getPath() );
return new Result(BitmapFactory.decodeStream(inputStream), NETWORK);
} catch (ExecutionException e) {
throw new IOException();
} catch (InterruptedException e) {
throw new IOException();
}
}
}
@premithk
Copy link
Author

picassoInstance= new  Picasso.Builder(this.activityContext.getApplicationContext())
.addRequestHandler(new FireBaseRequestHandler())
.build();

Should initialize picasso instance like this to use the request handler

@catalin-florescu
Copy link

Can you provide a usage example, please?

@anantshah93
Copy link

anantshah93 commented Jul 5, 2018

@catalin-florescu

Example:
Picasso picassoInstance = new Picasso.Builder(context)
.addRequestHandler(new @FireBaseRequestHandler(context))
.build();

picassoInstance.load(imageURL)
.fit().centerInside()
.into(mVHolder.imageView_post_tag);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment