Open In App

How to Add Images in RecyclerView using Firebase?

Last Updated : 14 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

It is a flexible Android view group that is basically used to display a large set of information in a scrollable manner. It is created to display large sets of data by reusing views as the user scrolls through the list, which provides smooth scrolling and less memory usage. It supports animations, images, texts, and touch event handling.

ImageView

ImageView is used to display an image or icons in a user interface. ImageView is a child class of the View class and is used with other views like TextView, and EditText to create a visually appealing and better user interface.

Firebase Database

It is a real-time database for mobile application development as well as web application development. It offers a wide range of services:

  1. Realtime Database
  2. Authentication
  3. Cloud Firestore
  4. Cloud Function
  5. Cloud Storage
  6. Hosting
  7. Analytics
  8. Messaging

In this, we will create a RecyclerView using firebase and we will integrate images using their URLs.

Step-by-Step Implementation

Step 1: Create a firebase project

New project creation

Step 2: Create a new project in android studio, connect it with firebase, and download all the SDKs required.

 

Step 3: Download the json file from the project setting, and integrate it into your Gradle.

json file

Step 4: In your activity_main write the code given below.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="1dp"
        android:layout_marginTop="1dp"
        android:layout_marginEnd="1dp"
        android:layout_marginRight="1dp"
        android:layout_marginBottom="1dp" />
 
</LinearLayout>


 

Step 5: Add data to your Firebase.

  • students as key in it 
  • s1 ( as student 1 ) in it 
  • course as key course name as the value
  • email as a key email address as value
  • name as key student name as the value
  • purl as key image url as value.

 

Step 6: Add these implementations to your gradle module.

implementation 'com.firebaseui:firebase-ui-database:8.0.2'
implementation 'com.github.bumptech.glide:glide:4.14.2'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.orhanobut:dialogplus:1.11@aar'

 

 

Note: Make to rebuild your gradle before adding code to MainActivity.

Step 7: Create a model class in your project. Add this code to it.

Java




package com.shruti.firebaserecyclerview;
 
public class model {
   
    String name, course, email,purl;
    model(){
 
    }
    public String getName() {
        return name;
    }
 
    public model(String name, String course, String email, String purl) {
        this.name = name;
        this.course = course;
        this.email = email;
        this.purl = purl;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getCourse() {
        return course;
    }
 
    public void setCourse(String course) {
        this.course = course;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    public String getPurl() {
        return purl;
    }
 
    public void setPurl(String purl) {
        this.purl = purl;
    }
}


Step 8: Create an xml file in your res folder > layout folder, name singlerow.xml. Add this code to it.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="5dp"
    android:elevation="5dp"
    app:cardUseCompatPadding="true">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="15dp">
 
        <de.hdodenhof.circleimageview.CircleImageView
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:src="@mipmap/ic_launcher"
            android:layout_centerVertical="true"
            android:id="@+id/img1"
            app:civ_border_width="2dp"
            app:civ_border_color="#FF000000"/>
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/nametext"
            android:text="Name"
            android:textStyle="bold"
            android:textSize="25sp"
            android:textColor="#000"
            android:layout_toRightOf="@id/img1"
            android:layout_marginLeft="10dp"/>
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/coursetext"
            android:text="Course Name"
            android:textSize="20sp"
            android:textColor="#000"
            android:layout_toRightOf="@id/img1"
            android:layout_below="@id/nametext"
            android:layout_marginLeft="10dp"/>
 
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/emailtext"
            android:text="Email"
            android:textSize="20sp"
            android:textColor="#000"
            android:layout_toRightOf="@id/img1"
            android:layout_below="@id/coursetext"
            android:layout_marginLeft="10dp"/>
 
    </RelativeLayout>
 
</androidx.cardview.widget.CardView>


 

Step 9: Create an adapter class and name it myadapter. Add the code given below.

Java




package com.shruti.firebaserecyclerview;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
 
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
 
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
 
import de.hdodenhof.circleimageview.CircleImageView;
 
public class myadapter extends FirebaseRecyclerAdapter<model,myadapter.myviewholder>
{
    public myadapter(@NonNull FirebaseRecyclerOptions<model> options) {
        super(options);
    }
 
    @Override
    protected void onBindViewHolder(@NonNull myviewholder holder, int position, @NonNull model model)
    {
        holder.name.setText(model.getName());
        holder.course.setText(model.getCourse());
        holder.email.setText(model.getEmail());
        Glide.with(holder.img.getContext()).load(model.getPurl()).into(holder.img);
    }
 
    @NonNull
    @Override
    public myviewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
    {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerow,parent,false);
        return new myviewholder(view);
    }
 
    class myviewholder extends RecyclerView.ViewHolder
    {
        CircleImageView img;
        TextView name,course,email;
        public myviewholder(@NonNull View itemView)
        {
            super(itemView);
            img=(CircleImageView)itemView.findViewById(R.id.img1);
            name=(TextView)itemView.findViewById(R.id.nametext);
            course=(TextView)itemView.findViewById(R.id.coursetext);
            email=(TextView)itemView.findViewById(R.id.emailtext);
        }
    }
}


Step 10: Create a menu folder in the res folder. Create a file name search.xml in the menu folder and below code to it.

Note: In drawable add a vector image of the search icon.

XML




<?xml version="1.0" encoding="utf-8"?>
    <item android:id="@+id/search_1"
        android:icon="@drawable/baseline_search_24"
        android:title="Search Data"
        app:showAsAction="always"
        app:actionViewClass="android.widget.SearchView"/>
</menu>


 

Step 11: In your Main Activity add this code given below.

Java




package com.shruti.firebaserecyclerview;
 
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
 
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;
 
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.FirebaseDatabase;
 
public class MainActivity extends AppCompatActivity {
   
   RecyclerView rview;
   myadapter adapter;
 
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
 
       rview = (RecyclerView)findViewById(R.id.rview);
       rview.setLayoutManager(new LinearLayoutManager(this));
 
       FirebaseRecyclerOptions<model> options =
               new FirebaseRecyclerOptions.Builder<model>()
                       .setQuery(FirebaseDatabase.getInstance().getReference().child("students"), model.class)
                       .build();
 
       adapter = new myadapter(options);
       rview.setAdapter(adapter);
 
   }
 
   @Override
   protected void onStart() {
       super.onStart();
       adapter.startListening();
   }
 
   @Override
   protected void onStop() {
       super.onStop();
       adapter.stopListening();
 
   }
 
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.search,menu);
 
       MenuItem item = menu.findItem(R.id.search_1);
 
       SearchView searchView = (SearchView)item.getActionView();
 
       searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
           @Override
           public boolean onQueryTextSubmit(String s) {
               processSearch(s);
               return false;
           }
 
           @Override
           public boolean onQueryTextChange(String s) {
               processSearch(s);
               return false;
           }
       });
       return super.onCreateOptionsMenu(menu);
   }
 
   private void processSearch(String s) {
 
       FirebaseRecyclerOptions<model> options =
               new FirebaseRecyclerOptions.Builder<model>()
                       .setQuery(FirebaseDatabase.getInstance().getReference().child("students"). orderByChild("name").startAt(s).endAt("\uf8ff") ,model.class)
                       .build();
       adapter = new myadapter(options);
       adapter.startListening();
       rview.setAdapter(adapter);
   }
}


Note: Change color codes accordingly in the values folder > colors.xml.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#27752A</color>
    <color name="purple_700">#4CAF50</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>


Output:

output

Note: Always use jpeg URL for the image. It only supports jpeg image URLs.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads