0

I want to delete specific node in customer table using post id.

 btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
            Query applesQuery = ref.child("customers").orderByChild("post").equalTo(postid);
            applesQuery.getRef().removeValue();
            Toast.makeText(getContext(), "deleted", Toast.LENGTH_SHORT).show();

        }
    });

But it deletes all database.

Milind
  • 5
  • 2

1 Answers1

3

The reason all nodes get deleted is in this line:

applesQuery.getRef().removeValue();

The Query.getRef() call returns the location that this query runs on. Since applesQuery is a query on post, applesQuery.getRef() returns the post node itself. So applesQuery.getRef().removeValue() removes the entire post node.

There is no concept of a "delete query" in Firebase, where you send DELETE FROM customer WHERE post = postid. Firebase can only delete a node when it knows its exact path. This means that you will need to execute the query, loop through its results and delete each of those.

In code:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query applesQuery = ref.child("customers").orderByChild("post").equalTo(postid);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            postSnapshot.getRef().removeValue()
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
}

Update: I now noticed that the value of the post property is the same as what you have as the key for the customer. If that is always the case you don't need a query to delete the node, and can just do:

ref.child("customers").child(postid).removeValue();
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Sir,sorry i mentioned wrong que..the actual is want to delete post by using post node in the table instead it deletes all post (n numbers of post are deleted if i want to delete specific post ). – Milind Oct 14 '18 at 14:55
  • I'm pretty sure that's what the code I shared does. If it doesn't work for you, edit your queston to show what you did with the code from my answer. Also note that I added a simpler version, since based on the JSON you showed you might not need a query. – Frank van Puffelen Oct 14 '18 at 14:58
  • By using your updated code...it giving error( java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()) – Milind Oct 14 '18 at 18:48
  • That means `postid` is `null`. – Frank van Puffelen Oct 14 '18 at 19:00