Reputation: 11
I built an application where I interact with firebase db. The structure is following.
game
question
-KiwYrNcX6B-VSLV8OmQ
titleofquestion
a:
"test"
b:
"test"
c:
"test"
Now to get my question object I did the following successfully.
databaseReference = FirebaseDatabase.getInstance().getReference().child("question");
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Question q = postSnapshot.getValue(Question.class);
listValues.add(q.getA());
keyValues.add(postSnapshot.getKey()); //This gives me the titleofquestion as a string.
Log.d(TAG, "keyValue: "+postSnapshot.getKey());
}
}
When I try to use this value to delete an entry in an another method
databaseReference.child(keyValues.get(position)).removeValue(); //
keyValues.get(position) gives me title of question
nothing happens.How can I fix this?
Edit: I think I should use listener for the remove operation as well but I am not sure
Upvotes: 0
Views: 918
Reputation: 599716
Your code boils down to:
databaseReference = FirebaseDatabase.getInstance().getReference().child("question");
keyValues.get(position) gives me title of question
databaseReference.child(keyValues.get(position)).removeValue(); //
So you're deleting the value at path: /question/<titleofquestion>
.
Your JSON structure does not match this path, because you have a push ID in there: /question/<pushid>/<titleofquestion>
. So the code you have (successfully) deletes a non-existing value.
I can think of two solutions:
From the JSON you shared we can't see why you have the level with the push ID in there. If that is not strictly needed, you can simplify the data model to:
game
question
titleofquestion
a:
"test"
b:
"test"
c:
"test"
And then your current code will already work.
If the push ID is needed in the data model, you will the entire path of each question in order to delete it.
So first you store the entire path instead of just the key:
databaseReference = FirebaseDatabase.getInstance().getReference().child("question");
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Question q = postSnapshot.getValue(Question.class);
listValues.add(q.getA());
keyValues.add(dataSnapshot.getKey()+"/"+postSnapshot.getKey()); //This gives the path to the question
}
}
And then you can delete the question with your current code:
databaseReference.child(keyValues.get(position)).removeValue();
keyValues.get(position) gives the path of question
Upvotes: 0
Reputation: 73
databaseReference.child(keyValues.get(position)).setValue("");
may be this, by setting the value of the key to ("") i.e. empty
Upvotes: 1