Breaking News

Create a Recycler View with Firebase Realtime Database

Create a Recycler View with Firebase Realtime Database

In this, we create a recycler view to show our fetched data from the firebase realtime database.




For reference of Firebase Realtime Database, Click here

For that,
  • Import recycler view library
  • Create a recycler view in XML
  • An adapter class to setup recycler view
  • Model class to interact with firebase database values
  • Set adpater on recycler view in java file.
Recycler view library in gradle file

app-level build.gradle
 implementation 'com.android.support:recyclerview-v7:29.0.0'  

Then we create a Recycler view in XML file.

XML file
 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout 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:layout_width="match_parent"  
   android:layout_height="wrap_content"  
   android:orientation="vertical"  
   android:layout_weight="2"  
   android:padding="10dp"  
   tools:context=".MainActivity">  
   
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:hint="Roll No"  
     android:id="@+id/student_roll"/>  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:hint="Name"  
     android:id="@+id/student_name"/>  
   <EditText  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:hint="Std"  
     android:id="@+id/student_std"/>  
   
   <Button  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:text="Add Student"  
     android:id="@+id/add_btn"/>  
   
   <LinearLayout  
     android:layout_width="match_parent"  
     android:layout_height="wrap_content"  
     android:layout_weight="2"  
     android:orientation="vertical">  
   
     <androidx.recyclerview.widget.RecyclerView  
       android:id="@+id/student_recycler_view"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:padding="5dp"  
       android:scrollbars="vertical"/>  
   
   </LinearLayout>  
 </LinearLayout>  

Then we create an adapter class that extends recycler view

adapter class
 package studio.harpreet.firebaseui;  
      
 import android.app.Activity;  
 import android.app.AlertDialog;  
 import android.content.Context;  
 import android.content.DialogInterface;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.ArrayAdapter;  
 import android.widget.EditText;  
 import android.widget.LinearLayout;  
 import android.widget.TextView;  
 import android.widget.Toast;  
   
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.recyclerview.widget.RecyclerView;  
   
 import com.google.firebase.database.FirebaseDatabase;  
   
 import java.util.List;  
   
 public class Student_ListAdaptor extends RecyclerView.Adapter<Student_ListAdaptor.Student_Model_Holder>  
 {  
   
   Context mctx;  
   List<StudentModel> student_list;  
   
   public Student_ListAdaptor(Context mctx, List<StudentModel> student_list) {  
     this.mctx = mctx;  
     this.student_list = student_list;  
   }  
   
   @NonNull  
   @Override  
   public Student_Model_Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {  
   
     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_custom_list,parent,false);  
   
     return new Student_Model_Holder(view);  
   }  
   
   @Override  
   public void onBindViewHolder(@NonNull Student_Model_Holder holder, int position) {  
   
     holder.rolltextview.setText(String.format("Roll No: %s", studentModel.rollno));  
     holder.nametextview.setText(String.format("Name: %s", studentModel.name));  
     holder.stdtextview.setText(String.format("Std: %s", studentModel.std));  
   
   }  
   
   @Override  
   public int getItemCount() {  
     return student_list.size();  
   }  
   
   public class Student_Model_Holder extends RecyclerView.ViewHolder {  
   
     TextView rolltextview,nametextview,stdtextview;  
   
     public Student_Model_Holder(@NonNull View itemView) {  
       super(itemView);  
   
       rolltextview = itemView.findViewById(R.id.roll_textview);  
       nametextview = itemView.findViewById(R.id.name_textview);  
       stdtextview = itemView.findViewById(R.id.std_textview);  
   
     }  
   }  
 }  

and in our java file, we will create a recycler view instance and also create an adapter class instance and set that adapter on recycler view. Whenever you want to update your recycler view, just call adapter.notifydatasetchanged();

Java file
 package studio.harpreet.firebaseui;  
   
 import android.content.DialogInterface;  
 import android.content.Intent;  
 import android.os.Bundle;  
 import android.view.View;  
 import android.widget.AdapterView;  
 import android.widget.Button;  
 import android.widget.EditText;  
 import android.widget.LinearLayout;  
 import android.widget.ListView;  
 import android.widget.Toast;  
   
 import androidx.annotation.NonNull;  
 import androidx.annotation.Nullable;  
 import androidx.appcompat.app.AlertDialog;  
 import androidx.appcompat.app.AppCompatActivity;  
 import androidx.recyclerview.widget.LinearLayoutManager;  
 import androidx.recyclerview.widget.RecyclerView;  
   
 import com.google.firebase.auth.FirebaseAuth;  
 import com.google.firebase.database.ChildEventListener;  
 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.Query;  
 import com.google.firebase.database.ValueEventListener;  
   
 import java.util.ArrayList;  
 import java.util.List;  
   
 public class MainActivity extends AppCompatActivity {  
   DatabaseReference databasestudent;  
   
   EditText roll_et,name_et,std_et;  
   Button add_btn;  
   
   RecyclerView recyclerView;  
   
   Student_ListAdaptor student_listAdaptor;     
   List<StudentModel > studentlist;  
   
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
   
     roll_et = findViewById(R.id.student_roll);  
     name_et = findViewById(R.id.student_name);  
     std_et = findViewById(R.id.student_std);  
   
     add_btn = findViewById(R.id.add_btn);  
   
     recyclerView = findViewById(R.id.student_recycler_view);  
     recyclerView.setHasFixedSize(true);  
     recyclerView.setLayoutManager(new LinearLayoutManager(this));  
     recyclerView.getLayoutManager().setMeasurementCacheEnabled(false);  
     studentlist = new ArrayList<>();  
   
     student_listAdaptor = new Student_ListAdaptor(this,studentlist);  
     recyclerView.setAdapter(student_listAdaptor);  
   
     databasestudent = FirebaseDatabase.getInstance().getReference("Student/3foBhguc0HK1mgjy03"); // Now this is your path  
   
     add_btn.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
   
        // startActivity(new Intent(MainActivity.this,About.class));  
         addstudent(roll_et.getText().toString().trim(),name_et.getText().toString().trim(),std_et.getText().toString().trim());  
   
       }  
     });    
   }  
   
   
   private void addstudent(String Rollno, String Name, String Std)  //Insert Method  
   {  
     String id = databasestudent.push().getKey();  
   
     StudentModel studentModel = new StudentModel(id,Rollno,Name,Std);  
   
     databasestudent.child(id).setValue(studentModel);  
   }  
   @Override  
   protected void onStart() {  
     super.onStart();  
   
     Query query = FirebaseDatabase.getInstance().getReference("Student/3foBhHK1mgjy03");  
   
     query.addValueEventListener(new ValueEventListener() {  
       @Override  
       public void onDataChange(@NonNull DataSnapshot dataSnapshot) {  
   
         studentlist.clear();  // because everytime when data updates in your firebase database it creates the list with updated items  
         // so to avoid duplicate fields we clear the list everytime  
         if(dataSnapshot.exists())  
         {  
           for(DataSnapshot studentsnapshot : dataSnapshot.getChildren())  
           {  
              StudentModel studentModel = studentsnapshot.getValue(StudentModel.class);  
   
              studentlist.add(studentModel);  
           }  
   
           student_listAdaptor.notifyDataSetChanged();  
         }  
   
       }  
   
       @Override  
       public void onCancelled(@NonNull DatabaseError databaseError) {  
   
       }  
     });  
   }  
 }  

 Next Post, create an item click on recycler view



Follow us for more posts like this, 
Subscribe Harpreet studio on Youtube  
Like Harpreet Studio on Facebook  
Follow me on Instagram 

No comments