My app is a monthly basis app. like every 1st of the month my app should do the calculations and update the data in firebase.. as there is no function like that I'm using a button(reset) on which when clicked do the calculations and update in Firebase but I don't know how to update all date child in all nodes please help me.
Till now I have tried this.
datarefoutstd = database.getReference("outstdln");
datarefoutstd.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot outsnapshot: snapshot.getChildren()) {
outsnapshot.child("date").setValue(snapshot.getValue(Long.class) 1);
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
CodePudding user response:
To increment by one the value of the date
property within all nodes, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference outstdlnRef = db.child("outstdln");
outstdlnRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
ds.child("date").getRef().setValue(ServerValue.increment(1));
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
This code will work only if you change the type of the date
property from String to a number. It's really a bad practice to store numbers as strings. You should always store the data according to its correct data type.