Android Tutorial

Software Setup and Configuration

Android Studio

File Structure

Components

Core Topics

Layout

View

Button

Intent and Intent Filters

Toast

RecyclerView

Fragments

Adapters

Other UI Component

Image Loading Libraries

Date and Time

Material Design

Bars

Working with Google Maps

Chart

Animation

Database

Advance Android

Jetpack

Architecture

App Publish

App Monetization

How to Delete Data from Firebase Firestore in Android?

To delete data from Firestore in an Android application, you need to perform the following steps:

  1. Setup Dependencies:

    Ensure that you've set up Firestore in your Android project. If not, add the dependency:

    implementation 'com.google.firebase:firebase-firestore:21.7.1' 
    // (or the latest version)
    
  2. Initialize Firestore:

    Initialize an instance of Firestore in your Activity or Fragment:

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    
  3. Delete a Document:

    To delete a document, you'll need the reference to the specific document:

    db.collection("yourCollectionName").document("yourDocumentId")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @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);
            }
        });
    
  4. Delete a Field:

    If you just want to delete a specific field from a document (instead of the whole document), you can use FieldValue.delete():

    DocumentReference docRef = db.collection("yourCollectionName").document("yourDocumentId");
    
    Map<String,Object> updates = new HashMap<>();
    updates.put("fieldName", FieldValue.delete());
    
    docRef.update(updates)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "Field successfully deleted!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error deleting field", e);
            }
        });
    
  5. Delete a Collection:

    Firestore does not natively support deleting an entire collection in one go. Instead, you would need to iterate over all the documents in the collection and delete them one by one. This can be achieved by fetching all documents and then deleting them in a loop, but be cautious as this can consume a lot of writes especially for large collections.

Remember, when working with Firestore, always consider the costs associated with reads, writes, and deletes. Deleting individual fields or documents can be straightforward, but handling larger amounts of data requires careful consideration.

  1. Remove document from Firestore in Android:

    • Use the delete() method on a DocumentReference to remove a document.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference documentRef = db.collection("yourCollection").document("yourDocumentId");
    
    documentRef.delete()
        .addOnSuccessListener(aVoid -> {
            // Document successfully deleted
        })
        .addOnFailureListener(e -> {
            // Handle errors
        });
    
  2. Firestore delete collection Android example:

    • Deleting a collection involves deleting each document within the collection individually.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    CollectionReference collectionRef = db.collection("yourCollection");
    
    collectionRef.get().addOnSuccessListener(queryDocumentSnapshots -> {
        for (QueryDocumentSnapshot document : queryDocumentSnapshots) {
            document.getReference().delete();
        }
    });
    
  3. Android Firestore delete field from document:

    • Use update() with an empty Map to remove a specific field from a document.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference documentRef = db.collection("yourCollection").document("yourDocumentId");
    
    Map<String, Object> updates = new HashMap<>();
    updates.put("fieldNameToDelete", FieldValue.delete());
    
    documentRef.update(updates)
        .addOnSuccessListener(aVoid -> {
            // Field successfully deleted
        })
        .addOnFailureListener(e -> {
            // Handle errors
        });
    
  4. Remove item from Firestore list in Android:

    • If your document has a list field, update the document by removing the item from the list.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference documentRef = db.collection("yourCollection").document("yourDocumentId");
    
    Map<String, Object> updates = new HashMap<>();
    updates.put("listField", FieldValue.arrayRemove("itemToRemove"));
    
    documentRef.update(updates)
        .addOnSuccessListener(aVoid -> {
            // Item successfully removed from the list
        })
        .addOnFailureListener(e -> {
            // Handle errors
        });
    
  5. Firestore batch delete in Android:

    • Use a WriteBatch to perform batch operations, including batch deletes.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    WriteBatch batch = db.batch();
    
    // Add documents to delete
    DocumentReference doc1 = db.collection("yourCollection").document("doc1");
    DocumentReference doc2 = db.collection("yourCollection").document("doc2");
    batch.delete(doc1);
    batch.delete(doc2);
    
    // Commit the batch
    batch.commit()
        .addOnSuccessListener(aVoid -> {
            // Batch successfully committed
        })
        .addOnFailureListener(e -> {
            // Handle errors
        });
    
  6. Code example for deleting data from Firestore in Android:

    • Combine the above snippets based on your specific use case.
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    DocumentReference documentRef = db.collection("yourCollection").document("yourDocumentId");
    
    documentRef.delete()
        .addOnSuccessListener(aVoid -> {
            // Document successfully deleted
        })
        .addOnFailureListener(e -> {
            // Handle errors
        });