Reputation: 29
I stuck with getting data from firebase and then push it back after some changes.
The code given below work with issues, because I need to get int and push sum of its and another value to the Realtime Database once, but it push it multiple times, after last time it was more than 39K rows, except 1.
private DatabaseReference ratingReference = FirebaseDatabase.getInstance().getReference().child(Consts.RATING_DB);
public void setRating(String uid, int addPoint) {
ratingReference.child(uid).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int rating = 0;
if (dataSnapshot.child(Consts.RATING).getValue() != null) {
rating = Integer.valueOf(dataSnapshot.child(Consts.RATING).getValue().toString());
}
DatabaseReference ref = ratingReference.child(getUid()).push();
Map<String, Object> ratingMap = new HashMap<>();
ratingMap.put("rating", rating + addPoint);
ref.updateChildren(ratingMap);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
I`ll be really grateful, if you help me, thanks a lot.
Upvotes: 0
Views: 60
Reputation: 138824
Assuming that the Consts.RATING
holds a String value similar with rating
and the type of this property is a number and not a String, to add the value of addPoint
to the existing rating
value, please use the following lines of code:
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long rating = 0;
if(dataSnapshot.child(Consts.RATING).exists()) {
rating = dataSnapshot.child(Consts.RATING).getValue(Long.class);
long newValue = rating + addPoint;
dataSnapshot.child(Consts.RATING).getRef().setValue(newValue);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ratingReference.child(uid).addListenerForSingleValueEvent(valueEventListener);
As you can see, there is no need to use any push()
call.
Upvotes: 1