为什么价值没有增加int Firebase数据库 [英] Why the value isn't increasing int Firebase database
问题描述
我对为什么它没有增加感到困惑.实际上,我正在制作一个投票面板,用户可以在其中进行投票,并且在投票时,它可以增加数据库.但这不会发生.
I am confused about why it is not increasing. Actually, I am making a voting panel, where user can vote and on voting, it increases database. But that doesn't happen.
int votes=0;
public void voteit(String party){
final int[] v = {0};
allpoliticalparty= FirebaseDatabase.getInstance().getReference().child("votes");
allpoliticalparty.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
v[0] =Integer.parseInt(value)+1;
}
@Override
public void onCancelled(DatabaseError error) {
}
});
votes=v[0]++;
allpoliticalparty.setValue("" + votes);
}
我也尝试过静态int选票= 0;然后它仅增加一次,而没有增加.
I have also tried static int votes=0; Then it increments only once then it didn't increases.
推荐答案
这不是增加值的正确方法.因为我们正在开发可在多用户环境中使用的应用程序,所以您应该考虑使用事务.请查看以下方法,它将帮助您增加/减少 votes
属性的值:
That's not a proper way in which you should incremenet a value. Because we are developing applications that can be used in a multiuser environment, you should consider using a transaction. Please see the following method, it will help you increase/decrease the value of your votes
property:
public static void setVotes(String operation) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference votesRef = rootRef.child("votes");
votesRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer votes = mutableData.getValue(Integer.class);
if (votes == null) {
return Transaction.success(mutableData);
}
if (operation.equals("increaseScore")) {
mutableData.setValue(votes + 1);
} else if (operation.equals("decreaseScore")){
mutableData.setValue(votes - 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
});
}
然后用:
setScore("increaseScore");
有关更多信息,请查看有关保存数据的官方文档作为交易.
For more informations please check the official documentation regarding saving data as transactions.
这篇关于为什么价值没有增加int Firebase数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!