How to display multiple data inserted into real time firebase database inside RecyclerView CardView example tutorial.
As in our previous tutorial we have discussed about Inserting data into Firebase real time database. This tutorial is the second part of that tutorial. In this tutorial we would going to Fetch the already inserted data into Firebase database and show that data into android application inside the custom RecyclerView + CardView. So here is the complete step by step tutorial for Show Firebase database data into RecyclerView ListView Tutorial.
Project Structure :
Activity Files in this project:
- MainActivity.java
- ShowStudentDetailsActivity.java
Layout files in this project:
- activity_main.xml
- activity_show_student_details.xml
- recyclerview_items.xml
Java files in this project:
- RecyclerViewAdapter.java
- StudentDetails.java
Contents in this project Show Firebase database data into RecyclerView ListView Tutorial :
1. Read our previous tutorial Inserting data into Firebase real time database. Because using this tutorial you can know how to insert data into firebase database using android application and how to configure firebase project in android studio properly.
2. Now open your Project’s build.gradle(Project) file.
3. Add classpath ‘com.google.gms:google-services:3.0.0’ inside dependencies block.
4. Open your project’s build.gradle(Module:app) file.
5. Add compile ‘com.android.support:recyclerview-v7:25.3.1’ ,
compile ‘com.android.support:cardview-v7:25.3.1’ ,
compile ‘com.android.support.constraint:constraint-layout:1.0.2’ ,
compile ‘com.firebase:firebase-client-android:2.4.0’ ,
compile ‘com.google.firebase:firebase-database:10.0.1’ inside dependencies block .
6. Then add apply plugin: ‘com.google.gms.google-services’ at the bottom of the page.
7. Now add below packagingOptions just bottom of buildTypes block like i did.
packagingOptions{ exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE-FIREBASE.txt' exclude 'META-INF/NOTICE' }
8. Screenshot after adding all above code :
9. Add Internet permission inside AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />
10. Add new Activity named as ShowStudentDetailsActivity in your current project. If you don’t know how to add new activity in Android Studio then read my this tutorial this will surely help you.
11. Now after creating activity ShowStudentDetailsActivity, it will automatically create a fresh layout file named as activity_show_student_details.xml in your layout section.
12. Now add RecyclerView widget in activity_show_student_details.xml file.
<android.support.v7.widget.RecyclerView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/recyclerView" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"> </android.support.v7.widget.RecyclerView>
13. Create RecyclerViewAdapter.java file .
package com.android_examples.firebaseinsertdata_android_examplescom; /** * Created by Juned on 8/9/2017. */ import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { Context context; List<StudentDetails> MainImageUploadInfoList; public RecyclerViewAdapter(Context context, List<StudentDetails> TempList) { this.MainImageUploadInfoList = TempList; this.context = context; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false); ViewHolder viewHolder = new ViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { StudentDetails studentDetails = MainImageUploadInfoList.get(position); holder.StudentNameTextView.setText(studentDetails.getStudentName()); holder.StudentNumberTextView.setText(studentDetails.getStudentPhoneNumber()); } @Override public int getItemCount() { return MainImageUploadInfoList.size(); } class ViewHolder extends RecyclerView.ViewHolder { public TextView StudentNameTextView; public TextView StudentNumberTextView; public ViewHolder(View itemView) { super(itemView); StudentNameTextView = (TextView) itemView.findViewById(R.id.ShowStudentNameTextView); StudentNumberTextView = (TextView) itemView.findViewById(R.id.ShowStudentNumberTextView); } } }
14. Create StudentDetails.java file.
package com.android_examples.firebaseinsertdata_android_examplescom; /** * Created by Juned on 7/25/2017. */ public class StudentDetails { private String name; private String phoneNumber; public StudentDetails() { // This is default constructor. } public String getStudentName() { return name; } public void setStudentName(String name) { this.name = name; } public String getStudentPhoneNumber() { return phoneNumber; } public void setStudentPhoneNumber(String phonenumber) { this.phoneNumber = phonenumber; } }
15. Create a custom layout file named as recyclerview_items.xml .
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/cardview1" android:layout_width="fill_parent" android:layout_height="wrap_content" card_view:cardElevation="5dp" card_view:contentPadding="5dp" card_view:cardCornerRadius="5dp" card_view:cardMaxElevation="5dp" > <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#ECEFF1" android:padding="10dp"> <TextView android:id="@+id/StudentName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Student Name: " android:textColor="#000" android:textSize="20dp" /> <TextView android:id="@+id/ShowStudentNameTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Show Student Name" android:textColor="#000" android:textSize="20dp" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/StudentName" android:layout_toEndOf="@+id/StudentName" android:layout_marginLeft="19dp" android:layout_marginStart="19dp" /> <TextView android:id="@+id/StudentNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Phone Number: " android:textColor="#000" android:textSize="20dp" android:layout_below="@+id/StudentName" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" /> <TextView android:id="@+id/ShowStudentNumberTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="Show Number" android:textColor="#000" android:textSize="20dp" android:layout_marginLeft="11dp" android:layout_marginStart="11dp" android:layout_below="@+id/ShowStudentNameTextView" android:layout_toRightOf="@+id/StudentNumber" android:layout_toEndOf="@+id/StudentNumber" /> </RelativeLayout> </android.support.v7.widget.CardView>
15. Declare DatabaseReference, ProgressDialog, List<StudentDetails> list = new ArrayList<>(), RecyclerView and RecyclerView.Adapter adapter objects in ShowStudentDetailsActivity file.
DatabaseReference databaseReference; ProgressDialog progressDialog; List<StudentDetails> list = new ArrayList<>(); RecyclerView recyclerView; RecyclerView.Adapter adapter ;
16. Assign ID’s to recyclerView, Progress dialog and set recyclerView layout using Linear layout manager.
recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(ShowStudentDetailsActivity.this)); progressDialog = new ProgressDialog(ShowStudentDetailsActivity.this); progressDialog.setMessage("Loading Data from Firebase Database"); progressDialog.show();
17. Assign FirebaseDatabase.getInstance().getReference to databaseReference and call database path name from MainActivity file.
databaseReference = FirebaseDatabase.getInstance().getReference(MainActivity.Database_Path);
18. Add addValueEventListener to databaseReference .
databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (DataSnapshot dataSnapshot : snapshot.getChildren()) { StudentDetails studentDetails = dataSnapshot.getValue(StudentDetails.class); list.add(studentDetails); } adapter = new RecyclerViewAdapter(ShowStudentDetailsActivity.this, list); recyclerView.setAdapter(adapter); progressDialog.dismiss(); } @Override public void onCancelled(DatabaseError databaseError) { progressDialog.dismiss(); } });
Complete source code for project Show Firebase database data into RecyclerView :
Code for MainActivity.java file.
package com.android_examples.firebaseinsertdata_android_examplescom; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.firebase.client.Firebase; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity { Button SubmitButton ; Button DisplayButton; EditText NameEditText, PhoneNumberEditText; // Declaring String variable ( In which we are storing firebase server URL ). public static final String Firebase_Server_URL = "https://insertdata-android-examples.firebaseio.com/"; // Declaring String variables to store name & phone number get from EditText. String NameHolder, NumberHolder; Firebase firebase; DatabaseReference databaseReference; // Root Database Name for Firebase Database. public static final String Database_Path = "Student_Details_Database"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Firebase.setAndroidContext(MainActivity.this); firebase = new Firebase(Firebase_Server_URL); databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path); SubmitButton = (Button)findViewById(R.id.submit); NameEditText = (EditText)findViewById(R.id.name); PhoneNumberEditText = (EditText)findViewById(R.id.phone_number); DisplayButton = (Button)findViewById(R.id.DisplayButton); SubmitButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { StudentDetails studentDetails = new StudentDetails(); GetDataFromEditText(); // Adding name into class function object. studentDetails.setStudentName(NameHolder); // Adding phone number into class function object. studentDetails.setStudentPhoneNumber(NumberHolder); // Getting the ID from firebase database. String StudentRecordIDFromServer = databaseReference.push().getKey(); // Adding the both name and number values using student details class object using ID. databaseReference.child(StudentRecordIDFromServer).setValue(studentDetails); // Showing Toast message after successfully data submit. Toast.makeText(MainActivity.this,"Data Inserted Successfully into Firebase Database", Toast.LENGTH_LONG).show(); } }); DisplayButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ShowStudentDetailsActivity.class); startActivity(intent); } }); } public void GetDataFromEditText(){ NameHolder = NameEditText.getText().toString().trim(); NumberHolder = PhoneNumberEditText.getText().toString().trim(); } }
Code for ShowStudentDetailsActivity.java file.