Integrating Firestore in Your Android App
Setting Permissions and Rules
- Define your Firestore security rules in the Firebase console for secure data access. For initial development, you might use less restrictive rules, but stricter validation is recommended for production.
- Ensure your app has the necessary internet permissions by adding the following line to your `AndroidManifest.xml`:
```xml
```
Basic Firestore Operations in Android
- **Adding Documents**: Use the following code to add a new document to a Firestore collection:
```java
// Create a new user with a first and last name
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);
// Add a new document with a generated ID
db.collection("users")
.add(user)
.addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});
```
- **Reading Documents**: Retrieve documents from a collection using:
```java
db.collection("users")
.get()
.addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.w(TAG, "Error getting documents.", task.getException());
}
}
});
```
Implementing Real-time Updates
- To keep your application updated with real-time changes to your Firestore database, use a snapshot listener:
```java
db.collection("users")
.addSnapshotListener(new EventListener() {
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listen:error", e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
Log.d(TAG, "New user: " + dc.getDocument().getData());
break;
case MODIFIED:
Log.d(TAG, "Modified user: " + dc.getDocument().getData());
break;
case REMOVED:
Log.d(TAG, "Removed user: " + dc.getDocument().getData());
break;
}
}
}
});
```
Updating Documents
- To update a document, specify the fields to update:
```java
DocumentReference userRef = db.collection("users").document("alovelace");
// Set the "isCapital" field of the city 'DC'
userRef
.update("born", 1816)
.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);
}
});
```
Deleting Documents
- For deleting a document, use:
```java
db.collection("users").document("alovelace")
.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);
}
});
```
Conclusion
- Leverage Google Firestore for building scalable and responsive applications with real-time capabilities. Explore and utilize Firestore features such as offline data persistence and complex querying for enhanced app functionality.