我有一个多项选择题应用程序,我想在获取之前的分数并将新分数添加到数据库后更新用户的分数。
我已经尝试借助以下方法来更新分数:
静态变量:它将重置先前存在的数据并覆盖其上的新数据。
局部变量:该值在匿名类中得到更新,但是当变量从匿名类中出来时,该值将反向返回。
public int total=1,correct=0,inCorrect=0;
public static int data=0;
if(total>5)
{
updateScore();
Log.i("Function","the updated value of data "+data);
Intent intent=new
Intent(QuizGeneral.this,ResultActivity.class);
String a= String.valueOf((correct));
intent.putExtra("correct",a );
a= String.valueOf((inCorrect));
intent.putExtra("incorrect",a);
startActivity(intent);}
private void updateScore(){
Log.i("Function","We are int the function now");
FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
Log.i("Function","We have got thr reference of the user");
String Uid=user.getUid();
Log.i("Function","Received the Uid"+Uid);
FirebaseDatabase db=FirebaseDatabase.getInstance();
Log.i("Function","received the instance");
final DatabaseReference
reference=db.getReference("Users/"+Uid+"/maths/");
Log.i("Function","we have got the reference");
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Log.i("Function","We are in anonymous function
now"+dataSnapshot.getValue().toString());
Object str = dataSnapshot.getValue();
Log.i("Function","We are getting the function now");
data= Integer.valueOf(str.toString());
//data2[0] = Integer.valueOf(str.toString());
Log.i("Function","the value is"+data);
Log.i("Function","correct value is"+correct);
Log.i("Function","the new value is"+data);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
// Log.i("Function","the value of data beffore setting to db is"+data);
int x=data+correct;
Log.i("Function","The correct value is"+x);
reference.setValue(x);
}
最佳答案
把这个`
int x=data+correct;
Log.i("Function","The correct value is"+x);
reference.setValue(x);`
在onDataChange()函数代码中。您将获得正确的结果。
发生这种情况是因为上面的代码在更改数据值和正确值之前运行,因此,如果在onDataChange函数中将此代码移出,则将获得正确的结果,因为在将数据值更新到Firebase之后。