Is it possible to update a specific child's value without ID or key in firebase realtime database from android on button click?

梦想与她 提交于 2020-01-25 08:34:08

问题


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:

  1. Perform a query to find the node(s) to update.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!