In this tutorial, you will see how to fetch data from Cloud Firestore and use it in your android application.
Prerequisites
Before you start this tutorial make sure you have:
- Android Studio 3.0 or higher
- An Android device or an emulator
Create a Firebase Project
Create an android project as usual.
Sign in to your google account in android studio.
Here’s an example of collection you wish to fetch data from:
Let us suppose you want to inflate your data onto this kind of layout:
First you need to define an instance of your database.
public class Test extends AppCompatActivity {
private FirebaseFirestore yourDB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
yourDB = FirebaseFirestore.getInstance();
}
Next, you need to define instance of the collection you want to fetch details from. It’s optional to do this inside any method according to your convenience.
@Override
public void onStart(){
super.onStart();
yourDB.collection("Doctors")
.document("abc@xyz.com")
.get()
.addOnCompleteListener
(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
DocumentSnapshot doc = task.getResult();
//set name next to Name TextView
(editText1.setText(doc.getString("Name"));
//set email next to Email TextView
(editText2.setText(doc.getString("Email")); //convert contact field from number to String
//set contact next to Contact TextView
(editText3.setText(doc.getLong("Contact").toString());
//similarly get all the other fields}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//print e.message();
}
});
}
Here, the methods used have following functionalities:
- .addOnCompleteListener( OnCompleterListener<TResult> listener ): Adds a listener that is called when the Task completes. The listener will be called on main application thread. If the Task is already complete, a call to the listener will be immediately scheduled. If multiple listeners are added, they will be called in the order in which they were added.
- <DocumentSnapshot>: It contains data read from a document in your Cloud Firestore database. The data can be extracted with the getData () or get(string) methods.
- onComplete( Task<TResult> task ): Called when the Task completes.
- .addOnFailureListener( OnFailureListener listener ): Adds a listener that is called if the Task fails. The listener will be called on main application thread. If the Task has already failed, a call to the listener will be immediately scheduled. If multiple listeners are added, they will be called in the order in which they were added.
- TResult getResult(): Gets the result of the Task, if it has already completed.
- Boolean isSuccessful(): Returns true if the Task has completed successfully; false otherwise.