Java 更新firebase实时数据库中密钥的值时出现问题
我有一个选择题应用程序。我想在获取以前的分数并将新分数添加到数据库后更新用户的分数 我已尝试在的帮助下更新分数- 静态变量:重置先前存在的数据并覆盖其中的新数据 局部变量:该值在匿名类中得到更新,但当变量从匿名类中出来时,该值会反转回来Java 更新firebase实时数据库中密钥的值时出现问题,java,android,firebase-realtime-database,Java,Android,Firebase Realtime Database,我有一个选择题应用程序。我想在获取以前的分数并将新分数添加到数据库后更新用户的分数 我已尝试在的帮助下更新分数- 静态变量:重置先前存在的数据并覆盖其中的新数据 局部变量:该值在匿名类中得到更新,但当变量从匿名类中出来时,该值会反转回来 public int total=1,correct=0,inCorrect=0; public static int data=0; if(total>5) { updateScore();
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);`
在函数代码中。您将得到正确的结果
之所以会发生这种情况,是因为上面的代码在更改data和correct的值之前运行,因此如果您在onDataChange函数中输出此代码,您将得到正确的结果,因为在更新值后,您的数据将被放入firebase。我找到了解决方案
有两种方法:
-addValueEventListener()-适用于每次数据更改或每次数据更改时触发
-addListenerForSingleValueEvent()-仅在数据更改时工作一次。当我在onDataChange()函数中使用这些函数时,值会不断增加,并且不会停止。现在2019-08-26 21:34:52.256 31154-31154/?I/功能:值为109911 2019-08-26 21:34:52.256 31154-31154/?I/功能:正确值为1 2019-08-26 21:34:52.256 31154-31154/?I/功能:新值为109911 2019-08-26 21:34:52.256 31154-31154/?I/功能:正确的值是109912 2019-08-26 21:34:52.257 31154-31154/?I/Function:我们现在使用匿名函数109912Indly建议任何其他解决方案…..可能发生这种情况,因为此匿名函数引用.addValueEventListener(new ValueEventListener(){@Override public void onDataChange(@NonNull DataSnapshot DataSnapshot)每次数据更改时都会被激活,因为我们正在更改函数本身中的数据,所以它每次都会递增,这个循环将永远持续下去。