问题描述:

I am new to FireBase . And i have seen many questions like this but didnt got 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

网友答案:

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.

相关阅读:
Top