本文介绍了使用Android版Firebase更新特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下创建的Firebase数据

I have a Firebase data created as follows

tasks
-K1NRz9l5PU_0R8ltgXz
   Description: "test1"
   Status: "PENDING"
 -K1NRz9l5PU_0CFDtgXz
   Description: "test2"
   Status: "PENDING"

我需要将第二个对象的状态从PENDING更新为COMPLETED.我正在使用updateChildren方法,但是它向任务子项添加了一个新节点.

I need to update the 2nd object's status from PENDING to COMPLETED. I am using the updateChildren method but it is added a new node to the tasks child.

如何在不创建新节点的情况下更新第二个节点的状态?

How do I update the status of the 2nd node without creating a new node?

这是我到目前为止的代码,

Here is my code as of now,

//在按钮上单击监听器

//on a button click listener

  {

    Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);        
    final Firebase objRef = m_objFireBaseRef.child("tasks");    
    Map<String,Object> taskMap = new HashMap<String,Object>();
    taskMap.put("Status", "COMPLETED");
    objRef.updateChildren(taskMap); //should I use setValue()...?

 });

推荐答案

您未指定要更新的任务的任务ID.

You're not specifying the task id of the task that you want to update.

String taskId = "-K1NRz9l5PU_0CFDtgXz";

Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);        
Firebase objRef = m_objFireBaseRef.child("tasks");
Firebase taskRef = objRef.child(taskId);
Map<String,Object> taskMap = new HashMap<String,Object>();
taskMap.put("Status", "COMPLETED");
taskRef.updateChildren(taskMap);

或者,您可以仅在要更新的属性上调用setValue()

Alternatively, you can just call setValue() on the property you want to update

String taskId = "-K1NRz9l5PU_0CFDtgXz";

Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);        
Firebase objRef = m_objFireBaseRef.child("tasks");
Firebase taskRef = objRef.child(taskId);
Firebase statusRef = taskRef.child("Status");
statusRef.setValue("COMPLETED");

或者:

Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);        
Firebase objRef = m_objFireBaseRef.child("tasks");
objRef.child(taskId).child("Status").setValue("COMPLETED");

更新

不确定我需要根据状态跟踪ID"是什么意思.但是,如果要同步状态为Pending的所有任务,则可以执行以下操作:

Update

Not sure what "I need to track the ID based on the status" means. But if you want to synchronize all tasks that are in status Pending, you'd do:

Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);        
Firebase objRef = m_objFireBaseRef.child("tasks");
Query pendingTasks = objRef.orderByChild("Status").equalTo("PENDING");
pendingTasks.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot tasksSnapshot) {
        for (DataSnapshot snapshot: tasksSnapshot.getChildren()) {
            snapshot.getRef().child("Status").setValue("COMPLETED");
        }
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});

这篇关于使用Android版Firebase更新特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 10:09