Issue
I am new to FireBase . And i have seen many questions like this but didn't get the solution. I want to know how can I update specific item in list. For example if i have list as
"fruits":{
0:{
name:"apple"
colour:"red"
}
1:{
name:"watermelon"
colour:"green"
}
now if i want to add new item to list i used push() because i dint wanted to save whole list again. it creates unique id to new item and list looks something like this
"fruits":{
0:{
name:"apple"
colour:"red"
}
1:{
name:"watermelon"
colour:"green"
}
KcfiFQZdzkK-TP8ZekZ:{
name:"Mango"
colour:"yellow"
}
}
now i want to update KcfiFQzdzkk* item. How can i update that item in list. Please help
Solution
If you want to update the color of the item with key KcfiFQZdzkK-TP8ZekZ
, you can simply write the value with:
mDatabase.child("fruits/KcfiFQZdzkK-TP8ZekZ/colour").setValue("red");
But it's more likely that you want to update the color of the node with name=mango and don't know its key.
In that case you first need to query the fruits to find the mango and then update its color:
mFruits.orderByChild("name").equalTo("Mango").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot fruitSnapshot: dataSnapshot.getChildren()) {
fruitSnapshot.getRef().child("colour").setValue("Red");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
In this second snippet you'll notice that we have to loop over all matching fruits in onDataChange
, since there can be multiple child nodes with name=Mango.
Answered By - Frank van Puffelen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.