如何在Firebase中保存用户分数并在Android Studio中实时检索分数
我正在创建一个应用程序,该应用程序中的按钮单击会增加点数,这些点数应保存到Firebase.我设法将这些数据保存到Firebase.但是,当我销毁我的应用程序并再次打开它时,点值显示相同,但是单击按钮后.再次从0开始.
I am creating an app in which points increases on button click and those points should be saved to firebase. I managed to save those data to firebase. But when I destroy my app and open it again the points value is showing same but after clicking button. It again starts from 0.
例如:每次单击按钮,积分值将增加到10点.现在,当我完全销毁该应用程序并再次打开它时,points值将显示相同,但是当再次单击该按钮时,它将从初始状态开始.
For example: every time on button click the points value increases to 10 points. Now when I completely destroy the app and open it again, the points value shows same, but when button clicked it again starts from initial condition.
这是我的代码
int amount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button_claim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
amount = amount + 100;
textView_points.setText(String.valueOf(amount));
databaseReference.setValue(textView_points.getText().toString());
}
});
}
@Override
protected void onStart() {
super.onStart();
if (mAuth.getCurrentUser() == null) {
finish();
Intent main = new Intent(this,MainActivity.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
}
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
textView_points.setText(dataSnapshot.getValue(String.class));
databaseReference.setValue(textView_points.getText().toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(Main2Activity.this,"error",Toast.LENGTH_LONG).show();
}
});
}
销毁应用之前 请参阅图片,在破坏应用程序并上传到数据库之前,单击按钮时点会增加 请参见图片1
再次打开应用程序(关闭后),它显示了相同的更新点 请参阅图片2
现在,当我单击要求"时,它将返回到100 请参阅图片编号3
请帮助我解决这个问题,我是新手 谢谢
please help me on this problem, and i am a newbie Thanks
2020年6月29日
现在也可以在不使用事务的情况下解决此问题.我们可以使用以下方法简单地增加一个值:
Now it's also possible to solve this problem without the use of a transaction. We can simply increment a value using:
rootRef.child("score").setValue(ServerValue.increment(1));
对于decremenet,需要以下代码行:
And for decremenet, the following line of code is required:
rootRef.child("score").setValue(ServerValue.increment(-1));
这是您在Firebase数据库中设置值的方式:
This is how you set a value in your Firebase database:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.child("score").setValue(1);
假设您的score
字段的类型为Integer,要解决此问题,请使用以下方法:
Assuming that the your score
field is of type Integer, to solve this, please use the following method:
public static void setScore(String operation) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
scoreRef.runTransaction(new Transaction.Handler() {
@Override
public Transaction.Result doTransaction(MutableData mutableData) {
Integer score = mutableData.getValue(Integer.class);
if (score == null) {
return Transaction.success(mutableData);
}
if (operation.equals("increaseScore")) {
mutableData.setValue(score + 1);
} else if (operation.equals("decreaseScore")){
mutableData.setValue(score - 1);
}
return Transaction.success(mutableData);
}
@Override
public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {}
});
}
为此,我建议您一定使用transactions
.如果用户尝试同时增加/降低分数,则可以避免错误的结果.因此,作为结论,请根据您的增加/减少操作调用此方法.
For this, I recommend you definitely use transactions
. You will avoid wrong results if users are trying to increase/decrease the score in the same time. So as a conclusion, call this method accordingly to your increase/decrease operation.
这是您如何阅读它:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Integer score = ds.getValue(Integer.class);
Log.d("TAG", score + "");
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
scoreRef.addListenerForSingleValueEvent(eventListener);