I have a Firebase data created as follows
tasks
-K1NRz9l5PU_0R8ltgXz
Description: "test1"
Status: "PENDING"
-K1NRz9l5PU_0CFDtgXz
Description: "test2"
Status: "PENDING"
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()...?
});
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);
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");
Or:
Firebase m_objFireBaseRef = new Firebase(AppConstants.FIREBASE_URL);
Firebase objRef = m_objFireBaseRef.child("tasks");
objRef.child(taskId).child("Status").setValue("COMPLETED");
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());
}
});
You can use code below to update
HashMap<String, Object> result = new HashMap<>();
result.put("Description", "Your Description comes here");
FirebaseDatabase.getInstance().getReference().child("tasks").child("-K1NRz9l5PU_0R8ltgXz").updateChildren(result);
It will update a specific child
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With