Is It Possible To Update A Specific Child's Value Without Id Or Key In Firebase Realtime Database From Android On Button Click?
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! [ent
Solution 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:
DatabaseReferenceref= FirebaseDatabase.getInstance().getReference("Cameras");
Queryquery= ref.orderByChild("Name").equalTo("TheNameOfTheNodeYouWantToUpdate");
query.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot cameraSnapshot: dataSnapshot.getChildren()) {
cameraSnapshot.getReference().child("Favorite").set(1);
}
}
@OverridepublicvoidonCancelled(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
:
DatabaseReferencefavRef= cameraSnapshot.getReference().child("Favorite");
favRef.runTransaction(newTransaction.Handler() {
@Overridepublic Transaction.Result doTransaction(MutableData mutableData) {
IntegercurrentValue= mutableData.getValue(Integer.class);
if (currentValue == null) {
mutableData.setValue(1);
} else {
mutableData.setValue(currentValue + 1);
}
return Transaction.success(mutableData);
}
@OverridepublicvoidonComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "transaction:onComplete:" + databaseError);
}
});
Post a Comment for "Is It Possible To Update A Specific Child's Value Without Id Or Key In Firebase Realtime Database From Android On Button Click?"