简体   繁体   中英

How to delete documents from firebase firestore using where clause inside OnClickListener

i want to check if a document already exists upon an on click listener.

if this document exists already, then it should be deleted and not added again.

i read firebase firestore documentation but they dont give much details about these matters.

so heres what i tried:

this is my onclick listener that will add a document to the database if none exist:

details_fave.setOnClickListener(new View.OnClickListener() {
  @Override
            public void onClick(View view) {
                Map<String,Object> fav = new HashMap<>();

                fav.put("shopID",SID);
                fav.put("usersID",UID);
                fav.put("ShopHeaderImg",sHI);
                fav.put("ShopProfileImg",sPI);
                fav.put("address",sA);
                fav.put("costEst",sCost);
                fav.put("country",sC);
                fav.put("latitude",sLat);
                fav.put("location",sL);
                fav.put("name",sN);
                fav.put("numTables",sNumTable);
                fav.put("ratings",sR);
                fav.put("summary",sSummary);
                fav.put("timing",sT);



                fStore.collection("Favorites").add(fav).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                    @Override
                    public void onSuccess(DocumentReference documentReference) {
                        Toast.makeText(DetailsActivity.this,"Saved", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(DetailsActivity.this,"Something went wrong", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

         

what i wanna do first is to check if the document exists or not, if it exists then delete it, if it doesnt then insert.

this is what i am trying to do to delete a record if found in a where clause:

 Task<QuerySnapshot> ref = fStore.collection("Favorites")
                .whereEqualTo("usersID", UID).whereEqualTo("shopID",SID)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                            for (QueryDocumentSnapshot document : task.getResult()) {
                                document.getReference().delete();
                            }
                        } else {
                            Log.d("whatever", "Error getting documents: ", task.getException());
                        }
                    }
                });

but still how would i implement it inside the onclick listener?

how can i do this with firebase firestore?

First of all you should separate your app from the evey logic around accessing your data.

Try using ViewModels for this.

Any way, I would do something like that:

 public void onClick(View view) {
    Map<String,Object> fav = new HashMap<>();

    fav.put("shopID",SID);
    fav.put("usersID",UID);
    fav.put("ShopHeaderImg",sHI);
    fav.put("ShopProfileImg",sPI);
    fav.put("address",sA);
    fav.put("costEst",sCost);
    fav.put("country",sC);
    fav.put("latitude",sLat);
    fav.put("location",sL);
    fav.put("name",sN);
    fav.put("numTables",sNumTable);
    fav.put("ratings",sR);
    fav.put("summary",sSummary);
    fav.put("timing",sT);

    Task<QuerySnapshot> ref = fStore.collection("Favorites")
            .whereEqualTo("usersID", UID).whereEqualTo("shopID",SID)
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        //if there is no document to delete the loop will exit without iterating even once
                        for (QueryDocumentSnapshot document : task.getResult()) 
                            document.getReference().delete();
                        //here we stand when we cleared the history of the user favorite list in the specific store, we can enter the new list
                        fStore.collection("Favorites").add(fav).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                            @Override
                            public void onSuccess(DocumentReference documentReference) {
                                Toast.makeText(DetailsActivity.this,"Saved", Toast.LENGTH_SHORT).show();
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(DetailsActivity.this,"Something went wrong", Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        Log.d("whatever", "Error getting documents: ", task.getException());
                    }
                }
            });

    
}

It's a bit of a mess, but it will get the job done.

If you have similar actions to preform that don't include querying document use TRANSACTIONS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM