Android App DevelopmentEducationProgramming

How to retrieve data from Firebase Realtime Database into Recycler View in Android

Hello Guys, We are back with a new topic. Today, we will discuss how to retrieve data from Firebase Realtime Database into Recycler View in Android. 

retrieve data from Firebase Realtime Databas

Firebase:

Firebase is a backend service that is ready to use immediately developed by Google to Develop High-Quality Apps. Including Machine Learning there are many features like real-time Database, Cloud messaging, Hosting, Storage, Analytics, Stream View, Testing your releases, Remote-Config, In-app Messaging in Firebase. 

Our Topic – Realtime Database

Realtime Database is used to store and retrieve data in real-time to all the users. Today, we will retrieve data from Realtime Database and display it in a Recycler View in Android Studio. For this topic, I’m going to use sample json data that consists of an image Url and image name. In this Implementation, we use Glide Library to display the Images from the URL in our App. 

Now Let’s got Implementation Part. First we have to create a Project in Forebase. To Create Projects Follow the below steps:

  • Go to Projects Setting and Click on Add App.
  • On the Next Screen, You are asked to Register your App.
  • Add your Package name there and click on Register App.
Register App
  • Now download google-services.json and add it in Android Studio Project in app folder.
  • Now add Required Dependencies in build.gradle files
download google-services.json

add these dependencies in app-level build.gradle file

dependencies{

 //Firebase
    implementation platform('com.google.firebase:firebase-bom:28.0.1')
    implementation 'com.google.firebase:firebase-analytics'
    implementation 'com.google.firebase:firebase-database'

}
apply plugin: 'com.google.gms.google-services'

Now add this in Project level build.gradle file

//project-level build.gradle

classpath 'com.google.gms:google-services:4.3.8'

I have Created a sample data Firebase Realtime database under Images node with ten items in the json.

realtime database

Advertisement

Now Let’s go to activity_main.xml file and design our Recyclerview

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    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/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:nestedScrollingEnabled="false"
        android:elevation="10dp"
        tools:targetApi="lollipop"/>


    <com.google.android.material.progressindicator.CircularProgressIndicator
        android:id="@+id/progress_circular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:indeterminate="true"/>

</RelativeLayout>

Now We have to Create Image item to display image.

item_image.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view_top"
    android:layout_width="match_parent"
    android:layout_height="280dp"
    android:foreground="?android:attr/selectableItemBackground"
    app:cardCornerRadius="5dp"
    app:cardElevation="3dp"
    app:cardUseCompatPadding="true">

    <RelativeLayout
        android:id="@+id/lyt_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/post_img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/light_gray"
            android:contentDescription="@string/app_name"
            android:scaleType="centerCrop" />

        <RelativeLayout
            android:id="@+id/lyt_secondary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@drawable/rectangle_transparent"
            android:padding="8dp">


            <TextView
                android:id="@+id/title_text"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginStart="8dp"
                android:maxLines="1"
                android:textColor="@color/white"
                android:textSize="14sp"
                tools:text="This"
                android:layout_marginLeft="8dp" />


        </RelativeLayout>

    </RelativeLayout>

</androidx.cardview.widget.CardView>

I have created a model class to fetch and store the data from firebase. Create an Imagemodel.java file and paste the below code.

package com.example.firebasedatabse;

public class Imagemodel {

    public String imageUrl;
    public String imagename;

    public Imagemodel(){

    }

    public Imagemodel(String imageUrl,String imagename){
        this.imageUrl = imageUrl;
        this.imagename = imagename;
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    public String getImagename() {
        return imagename;
    }

    public void setImagename(String imagename) {
        this.imagename = imagename;
    }
}

I have Created an Adapter Class to handle the fetched data. Create an ImageAdapter.java file and paste the below code inside it.

ImageAdapter.java

package com.example.firebasedatabse;

import android.app.Activity;
import android.content.Context;
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.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;

public class ImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    private Context mContext;
    private Activity mActivity;
    private ArrayList<Imagemodel> mContentList;

    public ImageAdapter(Context mContext, Activity mActivity, ArrayList<Imagemodel> mContentList) {

        this.mContext = mContext;
        this.mActivity = mActivity;
        this.mContentList = mContentList;

    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private CardView cardView;
        private ImageView imgPost;
        private TextView tvTitle;



        public ViewHolder(View itemView, int viewType) {
            super(itemView);

            // Find all views ids
            cardView = (CardView) itemView.findViewById(R.id.card_view_top);
            imgPost = (ImageView) itemView.findViewById(R.id.post_img);
            tvTitle = (TextView) itemView.findViewById(R.id.title_text);

        }

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder mainHolder, int position) {
        ViewHolder holder = (ViewHolder) mainHolder;


        final Imagemodel model = mContentList.get(position);
        // setting data over views
        String imgUrl = model.getImageUrl();
        if (imgUrl != null && !imgUrl.isEmpty()) {
            Glide.with(mContext)
                    .load(imgUrl)
                    .into(holder.imgPost);
        }

        holder.tvTitle.setText(model.getImagename());

    }

    @Override
    public int getItemCount() {
        return mContentList.size();
    }
}

Now Pastethe below Code in MainActivity.java. This Code retreives data from direbase and display it in Recyclerview.

MainActivity.java

package com.example.firebasedatabse;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.progressindicator.CircularProgressIndicator;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    CircularProgressIndicator progress_circular;
    RecyclerView recyclerView;
    DatabaseReference databaseReference;
    private Context mContext;
    private Activity mActivity;
    private ArrayList<Imagemodel> imagesList;
    private ImageAdapter imageAdapter = null;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        mActivity = MainActivity.this;
        mContext = getApplicationContext();
        FirebaseApp.initializeApp(this);

        recyclerView = findViewById(R.id.recycler_view);
        progress_circular = findViewById(R.id.progress_circular);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 2, GridLayoutManager.VERTICAL, false));
        recyclerView.setNestedScrollingEnabled(false);
        imagesList = new ArrayList<>();
        
        databaseReference = FirebaseDatabase.getInstance().getReference().child("Images");
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                imagesList.clear();
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    Imagemodel imagemodel = dataSnapshot.getValue(Imagemodel.class);
                    imagesList.add(imagemodel);
                }
                imageAdapter = new ImageAdapter(mContext,mActivity, (ArrayList<Imagemodel>) imagesList);
                recyclerView.setAdapter(imageAdapter);
                imageAdapter.notifyDataSetChanged();
                progress_circular.setVisibility(View.GONE);

            }

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

                Toast.makeText(MainActivity.this,"Error:" + error.getMessage(),Toast.LENGTH_SHORT).show();
            }
        });
        
    }
    
}

Finally, We have Finished. Now Using the above code you can retrieve data from firebase and display it in recycler view.

If you have any issues you can contact me using the Contact form or Comment on your Issue. I’ll try to solve it. Thank you. Stay Home Stay Safe.

Check Our Other Android Tutorials here

Happy Coding 🙂

Related Articles

Back to top button