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

标签 java android firebase-realtime-database

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

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

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

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

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/

相关文章:

java - 哪种更好的方式通过 Tomcat 提供文件(用于下载)?

java - 使用连续线程时 JVM 无缘无故关闭

java - 如何在 Spring Jms Tibjms 中在多个 VM 之间共享发布在主题上的消息

android - 为什么DDMS文件资源管理器中的应用程序名称以-1.apk或-2.apk结尾

java - myEclipse 首选项没有 Maven 选项

android - 无法从 onListItemClick 开始 fragment

java - ServiceTestCase<T>.getService?

swift - 如何在 Swift 中使用异步 Firebase 方法实例化一个类?

javascript - Uncaught ReferenceError : Firebase is not defined

javascript - 是否可以在 Firebase 中使用动态查询?