Reputation: 33
I would to update an existing value in my Firebase Realtime Database. I have tried several ways but none have worked. Anyone know how can I fix it? I attach the structure of the db if it can be useful and the code I have written so far. Thanks in advance to everyone
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
//loop through the keys
Map<String, Object> hashMap = new HashMap<>();
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(datasnap.child("email").getValue().toString().equals(email)) {
hashMap.put("address", "TEST1");
myRef.child(email).updateChildren(hashMap).addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
Toast.makeText(LocationActivity.this, "Data successfully update",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
Upvotes: 0
Views: 728
Reputation: 127
FirebaseFirestore ff = FirebaseFirestore.getInstance();
ff.collection("myCollection")
.document(myAuth.getCurrentUser().getUid())
.update("field",value)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
//for example Toast.makeText(context,getString(R.string.user_updated),Toast.LENGTH_SHORT).show();
}
}
});
Upvotes: 0
Reputation: 600006
You're updating the wrong location in the database, which means that either the write is now showing up in the screenshot or it is rejected (which your code doesn't handle).
To update the address
of the child node you're looping over:
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for(DataSnapshot datasnap : snapshot.getChildren()) {
datasnap.child("address").getRef().setValue("TEST1").addOnSuccessListener(new OnSuccessListener() {
@Override
public void onSuccess(Object o) {
Toast.makeText(LocationActivity.this, "Data successfully update",
Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
throw error.toException();
}
});
The key change here is that I call getRef()
on the snapshot, to get a reference to that specific location in the database.
You'll note that I also removed the two conditions, since neither of them had any effect on the outcome.
Upvotes: 1