Search code examples
androidfirebasegoogle-cloud-firestorefirebase-storagepicasso

How to load an image from Firestore and the Storage into a RecyclerView?


I didn't find any solution to this question, only for the Realtime Database. I managed to get a String from a document in Firestore and display it in the RecyclerView, I want to achieve the same with an image.

In my document in Firestore I have a field where a link of the picture (stored in the Storage) is saved as a string. I know that I somehow have to use Picasso to load the image, but I don't know how to do this.

Here is my code:

public class Prizes {

    private String text;
    private String image;


    public Prizes (){

    }

    public Prizes(String text, String image) {
        this.text = text;
        this.image = image;
    }
    public String getText() {
        return text;
    }
    public String getImage(){
        return image;
    }
}

Here is my Adapter:

public class PrizeGameAdapter extends FirestoreRecyclerAdapter<Prizes, PrizeGameAdapter.PrizeGameHolder> {

    public PrizeGameAdapter(@NonNull FirestoreRecyclerOptions<Prizes> options) {
        super(options);

    }

    @Override
    protected void onBindViewHolder(@NonNull PrizeGameHolder holder, int position, @NonNull Prizes model) {

        holder.textViewPrizeGame.setText(model.getText());
    }

    @NonNull
    @Override
    public PrizeGameHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.listitem_prize_game,parent, false);
        return new PrizeGameHolder(view);
    }

    class PrizeGameHolder extends RecyclerView.ViewHolder {

        TextView textViewPrizeGame;
        ImageView imageViewPrizeGame;

        public PrizeGameHolder(@NonNull View itemView) {
            super(itemView);

            textViewPrizeGame = itemView.findViewById(R.id.listitem_text_view_prize_game);
            imageViewPrizeGame = itemView.findViewById(R.id.picture_prize_recycler_view);
        }
    }
}

Solution

  • Its very simple to load the image from url into ImageView using Picasso.

    First, add the following line in dependencies build.gradle of your project and sync the project

    implementation 'com.squareup.picasso:picasso:2.71828'
    

    Sync the project and let the gradle download the picasso libaray. Once done then add following line of code inside onBindViewHolder of PrizeGameAdapter class

    Picasso.get()
    .load(model.getImage())
    .into(holder.imageViewPrizeGame);
    

    And viola, it will work for you.