Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaHow to populate RecyclerView with Firebase data using FirebaseUI in Android Studio

How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio

Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let’s connect the Realtime Database with an Android application and show the data in RecyclerView using the FirebaseUI. FirebaseUI is an open-source library for Android that provides to quickly connect common UI elements to Firebase APIs. We are going to cover the following things in this article.

  1. How to create a Firebase project and add some data manually to show in the app.
  2. How to create an Android project and add Firebase and FirebaseUI support in it.
  3. How to add RecyclerView in the android app and display the data in Firebase Realtime Database.

How to create a Firebase project and add data manually to show in the app

  • Step 1: Create a Firebase Project
    1. Go to https://console.firebase.google.com/u/0/
    2. Log in to Firebase with your Google account if are not already logged in.
    3. Click on create the project.

    Create a Firebase Project

  • Step 2: Give a name to the project
    1. Write the name.
    2. Click on continue.

    Give a name to your project.

  • Step 3: Disable Google Analytics(There is no need to do this for this project)
    1. Click on the toggle button.
    2. Click Continue.

    Disable Google Analytics

           Firebase will create a project for you and open it for you.

  • Step 4: Create a Realtime Database:
    1. Go to Develop Option on Sidebar.
    2. Click on Database.
    3. Scroll down in a new screen and click on Create Database on Realtime Database.
    4. Select Start in Test mode (In order to get read and write access to the database).
    5. Click enable.

    Create a Realtime Database.Select Realtime DatabaseStart in Test mode

  • Step 5: Add data to the database using the ‘+’ symbol in the database in the same manner as given in the picture.

    Add sample data in database

    Note:

    • All data values are stored in a string format for ease.
    • Key-value can be any string but should not include spaces ” “.
    • The same sub-keys should be present parent keys so that they can read by Recycler View without any error.

How to create an android project and add Firebase and FirebaseUI support in it

  • Step 1: Open Android Studio and create a new project named “RecyclerView” with an empty activity.
  • Step 2: Connect your Firebase project with your app.
  • Step 3: Add the following dependency in your app/build.gradle file in order to get the FirebaseUI and Firebase Realtime Database support in the app.




    dependencies {
       // Dependency FirebaseUI for Firebase Realtime Database
       implementation 'com.firebaseui:firebase-ui-database:6.2.1'
         
       // Dependency for Firebase REaltime Database
       implementation 'com.google.firebase:firebase-database:19.3.1'
       }

    
    

How to add RecyclerView in the android app and display the data in Firebase Realtime Database

  • Step 1: Add the following dependencies to get the support of Cardview in the app.




    dependencies {
        // This dependency includes all material components of the android app.
        implementation 'com.google.android.material:material:1.1.0'
       }

    
    
  • Step 2: First, add Recycler View in the activity_main.xml and name it recycler1 paste the given code in the activity_main.xml file in order to do so.

    XML




    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 
        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/recycler1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#65E4A6"/>
        
    </androidx.constraintlayout.widget.ConstraintLayout>

    
    
  • Step 3: Now, let’s create another XML file in the layout directory to store the data from the database of a particular person. We will name the file as person.xml. Copy the following code in the created file.

    XML




    <?xml version="1.0" encoding="utf-8"?>
    <androidx.cardview.widget.CardView 
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="20dp"
        android:scrollbars="vertical"
        app:cardCornerRadius="20dp">
      
      
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
      
            <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:text="First name: "
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />
      
            <TextView
                android:id="@+id/firstname"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textView1"
                app:layout_constraintTop_toTopOf="parent" />
      
            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:text="Last name:"
                android:textStyle="bold"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView1" />
      
            <TextView
                android:id="@+id/lastname"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:text="TextView"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textView2"
                app:layout_constraintTop_toBottomOf="@+id/firstname" />
      
            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginBottom="16dp"
                android:text="Age"
                android:textStyle="bold"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView2" />
      
            <TextView
                android:id="@+id/age"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginBottom="16dp"
                android:text="TextView"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toEndOf="@+id/textView3"
                app:layout_constraintTop_toBottomOf="@+id/lastname" />
      
        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>

    
    
  • Step 4: After this, We have to create a java file to fetch and store data of a particular person from the database and give it to Recycler View one by one. Create person.java in the same folder in which MainActivity.java file is present. Paste the following code in the file.

    Java




    // Your package name can be different depending
    // on your project name
    package com.example.recyclerview;
      
    public class person 
    {
        // Variable to store data corresponding
        // to firstname keyword in database
        private String firstname;
        
        // Variable to store data corresponding
        // to lastname keyword in database
        private String lastname;
        
        // Variable to store data corresponding
        // to age keyword in database
        private String age;
      
        // Mandatory empty constructor
        // for use of FirebaseUI
        public person() {}
      
        // Getter and setter method
        public String getFirstname() 
        
          return firstname;
        }
        public void setFirstname(String firstname)
        {
            this.firstname = firstname;
        }
        public String getLastname() 
        
          return lastname;
        }
        public void setLastname(String lastname)
        {
            this.lastname = lastname;
        }
        public String getAge() 
        
          return age; 
        }
        public void setAge(String age) 
        
          this.age = age;
        }
    }

    
    
  • Step 5: In order to show the data from person.java in person.xml, we have to create an Adapter class. Create another java file named personAdapter.java in the same folder as MainActivity.java and paste the following code.

    Java




    package com.example.recyclerview;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import androidx.annotation.NonNull;
    import androidx.recyclerview.widget.RecyclerView;
    import com.firebase.ui.database.FirebaseRecyclerAdapter;
    import com.firebase.ui.database.FirebaseRecyclerOptions;
      
    // FirebaseRecyclerAdapter is a class provided by
    // FirebaseUI. it provides functions to bind, adapt and show
    // database contents in a Recycler View
    public class personAdapter extends FirebaseRecyclerAdapter<
        person, personAdapter.personsViewholder> {
      
        public personAdapter(
            @NonNull FirebaseRecyclerOptions<person> options)
        {
            super(options);
        }
      
        // Function to bind the view in Card view(here
        // "person.xml") iwth data in
        // model class(here "person.class")
        @Override
        protected void
        onBindViewHolder(@NonNull personsViewholder holder,
                         int position, @NonNull person model)
        {
      
            // Add firstname from model class (here
            // "person.class")to appropriate view in Card
            // view (here "person.xml")
            holder.firstname.setText(model.getFirstname());
      
            // Add lastname from model class (here
            // "person.class")to appropriate view in Card
            // view (here "person.xml")
            holder.lastname.setText(model.getLastname());
      
            // Add age from model class (here
            // "person.class")to appropriate view in Card
            // view (here "person.xml")
            holder.age.setText(model.getAge());
        }
      
        // Function to tell the class about the Card view (here
        // "person.xml")in
        // which the data will be shown
        @NonNull
        @Override
        public personsViewholder
        onCreateViewHolder(@NonNull ViewGroup parent,
                           int viewType)
        {
            View view
                = LayoutInflater.from(parent.getContext())
                      .inflate(R.layout.person, parent, false);
            return new personAdapter.personsViewholder(view);
        }
      
        // Sub Class to create references of the views in Crad
        // view (here "person.xml")
        class personsViewholder
            extends RecyclerView.ViewHolder {
            TextView firstname, lastname, age;
            public personsViewholder(@NonNull View itemView)
            {
                super(itemView);
      
                firstname
                    = itemView.findViewById(R.id.firstname);
                lastname = itemView.findViewById(R.id.lastname);
                age = itemView.findViewById(R.id.age);
            }
        }
    }

    
    
  • Step 6: Then we have called the database and ask for data from it. This will be done in MainActivity.java itself.

    Java




    package com.example.recyclerview;
    import androidx.appcompat.app.AppCompatActivity;
    import androidx.recyclerview.widget.LinearLayoutManager;
    import androidx.recyclerview.widget.RecyclerView;
    import android.os.Bundle;
    import com.firebase.ui.database.FirebaseRecyclerOptions;
    import com.google.firebase.database.DatabaseReference;
    import com.google.firebase.database.FirebaseDatabase;
    import com.google.firebase.database.Query;
      
    public class MainActivity extends AppCompatActivity {
      
        private RecyclerView recyclerView;
        personAdapter
            adapter; // Create Object of the Adapter class
        DatabaseReference mbase; // Create object of the
                                 // Firebase Realtime Database
      
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
      
            // Create a instance of the database and get
            // its reference
            mbase
                = FirebaseDatabase.getInstance().getReference();
      
            recyclerView = findViewById(R.id.recycler1);
      
            // To display the Recycler view linearly
            recyclerView.setLayoutManager(
                new LinearLayoutManager(this));
      
            // It is a class provide by the FirebaseUI to make a
            // query in the database to fetch appropriate data
            FirebaseRecyclerOptions<person> options
                = new FirebaseRecyclerOptions.Builder<person>()
                      .setQuery(mbase, person.class)
                      .build();
            // Connecting object of required Adapter class to
            // the Adapter class itself
            adapter = new personAdapter(options);
            // Connecting Adapter class with the Recycler view*/
            recyclerView.setAdapter(adapter);
        }
      
        // Function to tell the app to start getting
        // data from database on starting of the activity
        @Override protected void onStart()
        {
            super.onStart();
            adapter.startListening();
        }
      
        // Function to tell the app to stop getting
        // data from database on stopping of the activity
        @Override protected void onStop()
        {
            super.onStop();
            adapter.stopListening();
        }
    }

    
    
  • Step 7: Before running the project In AndroidManifest.xml, one needs to include below permission, in order to access the internet:

    “uses-permission android:name=”android.permission.INTERNET”

Output:

RELATED ARTICLES

Most Popular

Recent Comments