gpt4 book ai didi

java - 更新 firebase 实时数据库中键的值时出现问题

转载 作者:行者123 更新时间:2023-12-02 09:34:28 24 4
gpt4 key购买 nike

我有一个多项选择题应用程序。我想在获取以前的分数并将新分数添加到数据库后更新用户得分。

我尝试在以下方面更新分数 -

静态变量:它重置以前存在的数据并覆盖其上的新数据。

局部变量:该值在匿名类中更新,但当变量从匿名类中出来时,它会反转。

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 一样。

关于java - 更新 firebase 实时数据库中键的值时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57661021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com