Hot questions for Using Glide in firebase realtime database

Top 10 Java Open Source / Glide / firebase realtime database

Question:

I have a problem about Glide. I want to download image with using Glide. When I use a link is working like this;

Glide.with(activity.this).load(pics direct url).into(imageview);

But when I use the Firebase Database is not working like this;

FirebaseDatabase firebasedatabase = FirebaseDatabase().getInstance().getReference(“name of database”).child(id).child(“imageUrl”);

Glide.with(activity.this).load(firebasedatabase).into(imageview);

Where is the wrong? How can I fix it? Thank you so much everyone!


Answer:

Your problem is that the following line returns FirebaseDatabase not a string:

FirebaseDatabase firebasedatabase = FirebaseDatabase().getInstance().getReference(“name of database”).child(id).child(“imageUrl”);

You need to listen to the string value when it's fetched and then add the Glide line like this:

firebasedatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String imageUrl = dataSnapshot.getValue(String.class);
            Glide.with(activity.this).load(imageUrl).into(imageview);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    })

Question:

I am able to retrieve text data successfully from firebase, but i got some difficulty in doing the same for images. I am using a recycler view and below is my recycler adapter:

public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder>{

    List<Listdata> listdata;

    public RecyclerviewAdapter(List<Listdata> listdata) {
        this.listdata = listdata;
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.myview,parent,false);

        MyHolder myHolder = new MyHolder(view);
        return myHolder;
    }


    public void onBindViewHolder(MyHolder holder, int position) {
        Listdata data = listdata.get(position);
        holder.vname.setText(data.getName());
        holder.vemail.setText(data.getEmail());
        holder.vaddress.setText(data.getAddress());

    }

    @Override
    public int getItemCount() {
        return listdata.size();
    }
    class MyHolder extends RecyclerView.ViewHolder{
        TextView vname , vaddress,vemail;
        ImageView thumbnail;


        public MyHolder(View itemView) {
            super(itemView);



            vname = (TextView) itemView.findViewById(R.id.vname);
            thumbnail = (ImageView) itemView.findViewById(thumbnail);
            vemail = (TextView) itemView.findViewById(R.id.vemail);
            vaddress = (TextView) itemView.findViewById(R.id.vaddress);

        }
    }


}

and here is activity code that initialises the process:

myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                list = new ArrayList<>();
                // StringBuffer stringbuffer = new StringBuffer();
                for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
                    Userdetails userdetails = dataSnapshot1.getValue(Userdetails.class);
                    Listdata listdata = new Listdata();
                    String name=userdetails.getName();
                    String email=userdetails.getEmail();
                    String address=userdetails.getAddress();
                    listdata.setName(name);
                    listdata.setEmail(email);
                    listdata.setAddress(address);
                    list.add(listdata);
                    // Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();

                }

                RecyclerviewAdapter recycler = new RecyclerviewAdapter(list);
                RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(InvestmentDrawer.this);
                recyclerview.setLayoutManager(layoutmanager);
                recyclerview.setItemAnimator( new DefaultItemAnimator());
                recyclerview.setAdapter(recycler);

            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                //  Log.w(TAG, "Failed to read value.", error.toException());
            }
        });
Glide.with(this)
             .load(imageData)
             .diskCacheStrategy(DiskCacheStrategy.ALL)
             .into(ivImgGlide);
        }

I would like to use the url entered in the database to load the images dynamically. Using glide or picasso. Below is the Listdata class

public class Listdata {

    public String name;
    public String address;
    public String email;

    public String imageurl;

    public String getImageUrl() {
        return imageurl;
    }

    public void SetImageUrl(String imageurl) {
        this.imageurl = imageurl;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Answer:

You can use Picasso or glide inside your onBindViewHolder

public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.MyHolder>{

List<Listdata> listdata;
Context context;

public RecyclerviewAdapter(List<Listdata> listdata,Context context) {
    this.listdata = listdata;
    this.context = context;
}

@Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.myview,parent,false);

    MyHolder myHolder = new MyHolder(view);
    return myHolder;
}


public void onBindViewHolder(MyHolder holder, int position) {
    Listdata data = listdata.get(position);
    holder.vname.setText(data.getName());
    holder.vemail.setText(data.getEmail());

    holder.vaddress.setText(data.getAddress());

      Glide.with(context)
         .load(data.getImageUrl())
         .diskCacheStrategy(DiskCacheStrategy.ALL)
         .into(holder.thumbnail);

     //with Picasso
      Picasso.with(context)
      .load(data.getImageUrl())
      .into(holder.thumbnail);

      // you need to define a method getImageUrl() to get the image url in Listdata
}

@Override
public int getItemCount() {
    return listdata.size();
}
class MyHolder extends RecyclerView.ViewHolder{
    TextView vname , vaddress,vemail;
    ImageView thumbnail;


    public MyHolder(View itemView) {
        super(itemView);



        vname = (TextView) itemView.findViewById(R.id.vname);
        thumbnail = (ImageView) itemView.findViewById(thumbnail);
        vemail = (TextView) itemView.findViewById(R.id.vemail);
        vaddress = (TextView) itemView.findViewById(R.id.vaddress);

    }
}



}

Remember you need to pass context from your parent activity into your adapter

In you onDataChanged you need to set the Image url using SetImageUrl()

@Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            list = new ArrayList<>();
            // StringBuffer stringbuffer = new StringBuffer();
            for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
                Userdetails userdetails = dataSnapshot1.getValue(Userdetails.class);
                Listdata listdata = new Listdata();
                String name=userdetails.getName();
                String email=userdetails.getEmail();
                String address=userdetails.getAddress();
                String imageUrl = userdetails.getImageUrl();
                listdata.setName(name);
                listdata.setEmail(email);
                listdata.setAddress(address);
                listdata.SetImageUrl(imageUrl);
                list.add(listdata);
                // Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();

            }

            RecyclerviewAdapter recycler = new RecyclerviewAdapter(list,getApplicationContext());
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(InvestmentDrawer.this);
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator( new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        }

Question:

i am building a chat application using firebase. I am using Glide to display images

Glide.with(getApplicationContext())
                        .load(imageUrl)
                        .crossFade()
                        .fitCenter()
                        .placeholder(R.drawable.loading)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(imageView);

I want to save the images to a specific folder in Internal Storage just like whatsapp does and load images from there after it has been saved.Images are uploaded on Firebase Storage and its URL is saved in Firebase Database and i load them in a imageView with the url using Glide


Answer:

    private static final String IMAGE_DIRECTORY = "/yourfoldername/images";

    //this method return your folder image path
    public String saveImage(Bitmap myBitmap) {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            File wallpaperDirectory = new File(
                    Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
            // have the object build the directory structure, if needed.
            if (!wallpaperDirectory.exists()) {
                wallpaperDirectory.mkdirs();
            }
            try {
                File f = new File(wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg");
                f.createNewFile();
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
                MediaScannerConnection.scanFile(this,
                        new String[]{f.getPath()},
                        new String[]{"image/jpeg"}, null);
                fo.close();
                Log.d("TAG", "File Saved::--->" + f.getAbsolutePath());

                return f.getAbsolutePath();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return "";
        }


    // glide load image
    Glide.with(this)
        .load(imageUrl)
        .asBitmap()
        .into(new SimpleTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {

                String imagepath = saveImage(resource);
// Parse the gallery image url to uri
                Uri savedImageURI = Uri.parse(imagepath);



// Display the saved image to ImageView
            iv_saved.setImageURI(savedImageURI);

            }
        });