Reputation: 11
I have a button which updates the int data value in database but I want to do an addition of a value to an existing integer data in Firebase Realtime Database not just by replacing it with another value.
The current integer value is 400 in the child of "points". I wanted to add a number to it and then update it. For example, if I add 200, it will update the data inside the firebase and then display 600 there.
Would really appreciate if anyone can help me with this?
Main code:
Button btnDone;
DatabaseReference DBR;
int z = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tapcard);
btnDone = findViewById(R.id.buttonDone);
DBR = FirebaseDatabase.getInstance().getReference().child("Member");
btnDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
DBR.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.getChildrenCount();
for (z = 1; z < count + 1; z++) {
DBR = FirebaseDatabase.getInstance().getReference().child("Member").child(String.valueOf(z));
DBR.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("points").setValue(100);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Intent i = new Intent(TapCardActivity.this, HomeActivity.class);
startActivity(i);
}
});
}
Rewards class:
public class RewardsClass implements Serializable {
private String Name;
private String Description;
private int img;
private int points;
public RewardsClass(String name, String description, int img, int points) {
Name = name;
Description = description;
this.img = img;
this.points = points;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public int getImg() {
return img;
}
public void setImg(int img) {
this.img = img;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
Upvotes: 1
Views: 1876
Reputation: 599571
The easiest way to add a value to a property in the Realtime Database is by using the (pretty new) increment()
operation.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("Member").child(String.valueOf(z));
userRef.child("points").setValue(ServerValue.increment(200));
Also see:
Upvotes: 2