Home > OS >  The player exits the game activity, and the room should be removed only by him, but the rooms of all
The player exits the game activity, and the room should be removed only by him, but the rooms of all

Time:07-27

I'm making a game, when the player exits the game activity, the room he created is deleted, the problem is that in the "rooms/" path, all its contents are deleted, not just the player's room. In general, the player leaves are removed except for his room, others, and how to fix it.

The example of this photo shows how there are two rooms in rooms, when a player leaves one room, two are removed.

enter image description here

Here is the code that I am using:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Query applesQuery = ref.child("rooms").orderByChild(roomName);

        applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot appleSnapshot: dataSnapshot.getChildren()) {
                    appleSnapshot.getRef().removeValue();
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });

CodePudding user response:

When you're creating a query and you're attaching a listener to it, you get as a result a DataSnapshot object that contains all that data. When you iterate through the results and you call:

appleSnapshot.getRef().removeValue();

It means that you remove every child in the DataSnapshot object. If you want, for example, to only remove Ben, there is no need for a query. You can simply create a reference that points to Ben's node and call removeValue() like this:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference benRef = db.child("rooms").child("Ben");
benRef.removeValue();

You can also attach a listener to the operation if you want, to see if something goes wrong.

  • Related