问题
this is my database and now I need to change the value of favorite from 0 to 1 but I don't have any specific id so how can I change specific child's value on click in android!
[enter image description here][1]
回答1:
In order to update a node, you must know the complete path to that node.
Firebase does not support the concept of update queries, where you can pass a condition to an update statement. So if you don't know the complete path, you will have to take a two-step approach:
- Perform a query to find the node(s) to update.
- Update each node.
Say that for example the Name property identifies the nodes you want to update, you could do that with:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Cameras");
Query query = ref.orderByChild("Name").equalTo("TheNameOfTheNodeYouWantToUpdate");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot cameraSnapshot: dataSnapshot.getChildren()) {
cameraSnapshot.getReference().child("Favorite").set(1);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
Given that you're updating a counter in the above, you'll actually probably want to use a transaction inside that onDataChange:
DatabaseReference favRef = cameraSnapshot.getReference().child("Favorite");
favRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer currentValue = mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(1);
} else {
mutableData.setValue(currentValue + 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "transaction:onComplete:" + databaseError);
}
});
来源:https://stackoverflow.com/questions/58968448/is-it-possible-to-update-a-specific-childs-value-without-id-or-key-in-firebase