Cloud Firestore in Android Studio
How to read, write and update data in Cloud Firestore - Using Android Studio and Java
What is Cloud Firestore Database?
Cloud Firestore is a cloud NoSQL database used to read, write, and update data inside an android, iOS, or web application. The data in the Firestore is stored in the form of documents, so it becomes easy to manage this data inside Firebase. Cloud Firestore stores data in Documents, which are stored in Collections.
Setting up Firebase
Adding Firebase to Android Project
Working with Cloud Firestore Database
Initialize Cloud Firestore
// Access a Cloud Firestore instance from the Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();
Write Data
Data in a document is stored in the form of key-value pairs. Hence, we use HashMap to create an object of the data. And store this object in the Firestore Database.
// A user object containing name and phone
Map<String, Object> user = new HashMap<>();
user.put("name", "Person1");
user.put("phone", "01234");
Let's say that the database looks like users
-> userId
-> user
as shown below.
Now let's add the user
object we created above to the database.
// Uses an auto-generated ID for `userId`
db.collection("users") // name of the collection
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
// data added successfully
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// show an error message
}
});
If we want to assign the user
object to a specific userId
, we can do it as shown below.
String userId = "xyz";
db.collection("users") // name of the collection
.document(userId) // name of the document
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
//data added successfully
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// show an error message
}
});
In this way, we can write the data in the Cloud Firestore Database.
Read Data
get()
method is used to retrieve the entire collection.
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
//`task.getResult()` is a list of documents
// belonging to the collection = "users"
for (QueryDocumentSnapshot document : task.getResult()) {
String name = (String) document .get("name");
String phone = (String) document .get("phone");
}
} else {
// show an error message
}
}
});
Note that we can also use
onSuccessListener
(along withonFailureListener
) instead ofonCompleteListener
.onSuccessListener
would directly returnDocumentSnapshot
instead ofTask
db.collection("users")
.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot!=null){
for (QueryDocumentSnapshot document : documentSnapshot) {
String name = (String) document .get("name");
String phone = (String) document .get("phone");
}
}
}
});
But, this way, we can't detect any real-time changes to the database.
To detect the real-time changes to the database, we can use SnapshotListener
String userId = "xyz";
db.collection("users")
.document(userId)
.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot,
@Nullable FirebaseFirestoreException error) {
if (documentSnapshot!=null){
String name = (String) documentSnapshot.get("name");
String phone = (String) documentSnapshot.get("phone");
}
}
});
Update Data
Let's update the phone
of the user with a specific userId
, to "11111"
HashMap<String, Object> user = HashMap<>();
user.put(phone, "11111"); // the data to be updated
String userId = "xyz";
db.collection("users") // name of the collection
.document(userId)
.update(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
// data updated successfully
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
// show an error message
}
});
In this way, we can easily use Cloud Firestore to read, write and update data in an android application.
Also Read: Cloud Firestore v/s Realtime Database