Android Firebase Firestore Basics List Data

Hello Guys Today We Are Going To Learn Some Basics Of Firebase Firestore Adding And Retrieving Data in List

Its a type of Realtime Database but much more than the old Fashioned Realtime Database.It Supports Auto Scaling and can handle much more powerful queries and multiple queries too.

Note: Watch This Video or Continue Reading Blog They Both Are Same.

So in this Tutoriali am gonna teach you some basics of Firebase Firestore.
We are simply going to save our name and our Friends name in the Firestore
And then retrive them all and show in our ListView
Lets Start Coding.

  • Create a Project in Firebase
  • Add Your Android App in to your Firebase Project
  • open Database And Choose Firestore
  • Select Mode for Learning perpose
  • Add this dependency in your app level gradle
   compile 'com.google.firebase:firebase-firestore:11.8.0'  

Now Lets Code Our Layout File:

 <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="match_parent"
android:orientation="vertical"
tools:context="com.theandroidclassroom.firestoredemo.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="enter Name"
android:id="@+id/edittext"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="add Data"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView"/>
</LinearLayout>

So here we need an EditText to get name, Button to save the data in Firestore And a ListView to show all our Friends List.

Now lets start Coding our MainActivity.Java class
here’s my MainActivity.Java:

 package com.theandroidclassroom.firestoredemo;  
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn)
Button button;
@BindView(R.id.edittext)
EditText editText;
@BindView(R.id.listView)
ListView listView;
private List<String> namesList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
final FirebaseFirestore db = FirebaseFirestore.getInstance();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Map<String,String> map = new HashMap<>();
map.put("name",editText.getText().toString());
db.collection("group").document().set(map).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(getApplicationContext(),"Data saved",Toast.LENGTH_SHORT).show();
}
}
});
}
});
db.collection("group").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
namesList.clear();
for (DocumentSnapshot snapshot : documentSnapshots){
namesList.add(snapshot.getString("name"));
}
ArrayAdapter<String>adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_selectable_list_item,namesList);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
});
}
}

Confused What happening here? Dont worry i will explain:

  1. So first we created an Intance of Firestore:
  2.  final FirebaseFirestore db = FirebaseFirestore.getInstance();  
  3. Now on our button onClickListner we created a Hash map with key and value both as Strings as it is required by the Firestore:
  4.  Map<String,String> map = new HashMap<>();  
    map.put("name",editText.getText().toString());
  5. Now what we have to do is create a collection in our Firestore (you can give any name to your collection) and then add the document with auto generated Id document is going to be our Hash map that we created Earlier and Now just set this Hash map to the Document :
  6.   db.collection("group").document().set(map).addOnCompleteListener(new OnCompleteListener<Void>() {  
    @Override
    public void onComplete(@NonNull Task<Void> task) {
    if (task.isSuccessful()){
    Toast.makeText(getApplicationContext(),"Data saved",Toast.LENGTH_SHORT).show();
    }
    }
    });
  7. Now we have Added The Data in Our Firebase Firestore. To Alert The user On Successfully Addition of data we will use on CompleteListener and if task is successful Toast a success Message.
Congrats! The Adding Part is Successfully  Done Now Lets Start Retrieving Data.
  1. To Retrieve the data we have to give Collection name to our Firestore Instance then Add a SnapShotListener as it will listen to any modification, Addition Or Removal of our Data in Realtime.
  2. On Event we get the instance of QuerySnapshot Actually it is the list of all the documents of our Collection. So now we will use ForEach loop to add the data of each document into our String List by giving the correct keyname:
  3.   for (DocumentSnapshot snapshot : documentSnapshots){  
    namesList.add(snapshot.getString("name"));
    }
  4. Now Lets just create an ArrayAdapter by giving our this string list And attach it on our listview: 
  5.   ArrayAdapter<String>adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_selectable_list_item,namesList);  
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);

Hurray! We Have Successfully Retrieved The Data and set it on  our Listview.
Okay guys this is much for this Tutorial if You have any Doubts please watch my Video on YouTube and please like share and Subscribe Channel TheAndroidClassroom. Feel free to ask me any Questions on Comment I will be Always there to help You.
Link of my YouTube Channel:
TheAndroidClassroom

MainActivity.class
MainActivity.class

Leave a Reply

Your email address will not be published. Required fields are marked *