Java Android App Development Course, Cloud Firestore

In this post, we will take a detailed look at how to develop Android apps using Java and how to store data using Google Cloud Firestore.

1. What is Cloud Firestore?

Cloud Firestore is Google’s NoSQL cloud database that supports real-time data synchronization and offline capabilities. Firestore can scale horizontally and is also referred to as a real-time database. It can be easily used across various platforms and is particularly easy to integrate with mobile applications.

Firestore uses the concept of collections and documents for data storage. A collection contains multiple documents, and a document is a unit of data consisting of key-value pairs. This structure makes data modeling very flexible.

2. Key Features of Firestore

  • Real-time data synchronization
  • Offline support
  • Data protection through security rules
  • Scalability and flexibility
  • Support for various languages and platforms

3. Setting Up Firestore

3.1. Creating a Firebase Project

The first step is to create a new project in the Firebase console. Follow the steps below:

  1. Go to the Firebase website and log in.
  2. Click the ‘Add Project’ button and enter the required information.
  3. Firebase Analytics is optional, so set it up only if needed.
  4. Once the project is created, navigate to the ‘Firestore Database’ menu and activate Firestore.
  5. Set up security rules and choose the database mode.

3.2. Adding Firestore in Android Studio

After setting up the Firebase project, create a project in Android Studio. Use Gradle to add the necessary Firebase dependencies.


implementation "com.google.firebase:firebase-firestore-ktx:24.0.0"

You are now ready to initialize Firebase and use the Firestore instance.

Additionally, you need to add the google-services.json file to the app folder of your project to initialize Firebase. This file can be downloaded during the Firebase project creation.

You can initialize Firestore with the following code snippet:


FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("YOUR_APP_ID") // Required
.setApiKey("YOUR_API_KEY") // Required
.setDatabaseUrl("YOUR_DATABASE_URL") // Required
.setProjectId("YOUR_PROJECT_ID") // Required
.build();
FirebaseApp.initializeApp(context, options);

To get the Firestore instance, you can use the following code:


FirebaseFirestore db = FirebaseFirestore.getInstance();

4. Basic CRUD Operations in Firestore

Data handling in Firestore is carried out through the Create, Read, Update, Delete (CRUD) processes.

4.1. Adding Data (Create)

To add data, you can use the set or add methods.

The set method is used to explicitly create or update a document. The below example shows how to add user information to Firestore:


Map user = new HashMap<>();
user.put("first", "John");
user.put("last", "Doe");
user.put("age", 30);

db.collection("users").document("userID123")
.set(user)
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot added with ID: " + "userID123");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});

4.2. Reading Data (Read)

To read the data of a document, you can use the get method. Below is an example of reading the data of a specific document:


DocumentReference docRef = db.collection("users").document("userID123");
docRef.get().addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d(TAG, "Document data: " + document.getData());
} else {
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});

4.3. Updating Data (Update)

To update an existing document, use the update method:


DocumentReference docRef = db.collection("users").document("userID123");
docRef.update("age", 31)
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully updated!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error updating document", e);
}
});

4.4. Deleting Data (Delete)

To delete a document, use the delete method:


db.collection("users").document("userID123")
.delete()
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully deleted!");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error deleting document", e);
}
});

5. Firestore Real-time Database Functionality

One of the powerful features of Firestore is its real-time data synchronization capability. Below is how to receive real-time updates of data changes using Firestore listeners:


db.collection("users")
.document("userID123")
.addSnapshotListener(new EventListener() {
@Override
public void onEvent(@Nullable DocumentSnapshot documentSnapshot,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}

if (documentSnapshot != null && documentSnapshot.exists()) {
Log.d(TAG, "Current data: " + documentSnapshot.getData());
} else {
Log.d(TAG, "Current data: null");
}
}
});

6. Setting Security Rules

You must set up security rules for Firestore to enhance the security of the database. By default, all users are granted read and write access to the data. You can manage user authentication and permissions by setting security rules.

For example, you can require user authentication and allow users to read or write only their own data. An example is as follows:


rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}

7. Conclusion

In this tutorial, we explored how to develop Android apps using Java and integrate with Cloud Firestore. Firestore offers various features and is used by many developers as a suitable data store for mobile applications.

The real-time data synchronization feature and offline support of Firestore are conducive to enhancing user experience. The security rules of Firebase also ensure the stability of data.

I hope this post helps you in your Android app development. If you have any further questions, please leave a comment!