Issue
I have a button it's a counter doing plus 1 if "stars" child hasn't true otherwise -1 .with first press doing 2 statements which have below. Actually, I must keep my UID in userkey
child but with the first press being deleted meanwhile my starcount be adding normally it must go to stars child delete from there but this directly removes wherever exists my UID.
final String uid = currentUser.getUid();
DatabaseReference allfeed = db.getReference("allfeed").child(post_key);
allfeed.runTransaction(new Transaction.Handler() {
@NonNull
@Override
public Transaction.Result doTransaction(@NonNull MutableData currentData) {
ExampleItem star = currentData.getValue(ExampleItem.class);
if (star == null) {
return Transaction.success(currentData);
}
if (star.stars.containsKey(uid)) {
star.starCount = star.starCount - 1;
star.stars.remove(uid);
} else {
// Star the post and add self to stars
star.starCount = star.starCount + 1;
star.stars.put(uid, true);
}
currentData.setValue(star);
return Transaction.success(currentData);
}
@Override
public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {
}
});
public class ExampleItem {
public ExampleItem(){
}
String userid,key,reply,time,text,username;
public int starCount = 0;
public Map<String, Boolean> stars = new HashMap<String, Boolean>();
//
// GETTER AND SETTER
//
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<>();
result.put("keyuser", userid);
result.put("username", username);
result.put("text", text);
result.put("key", key);
return result;
}
}
Solution
When you try to map a node from the Firebase Realtime Database into an object of type ExampleItem
using:
ExampleItem star = currentData.getValue(ExampleItem.class);
It means that each field in the class will hold the value of the corresponding field that exists in the node. This means that all fields in the class should have an exact match in the database.
Since every node, in the Firebase Realtime Database, can be considered a Map, when you are using the setValue() method:
currentData.setValue(star);
It means that you overwrite the data at that specific location. Since your ExampleItem
class doesn't have a field called userKey
, that field from the database will be removed. Hence that (highlighted read) remove operation. To solve this, you have to change the field in your class from:
String userid,key,reply,time,text,username;
👆
To:
String userid,userKey,reply,time,text,username;
👆
In this way, the userKey
field will not be deleted anymore.
Answered By - Alex Mamo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.