0

I want to get a value from Firebase DB. I have a score and I want to check previous value on DB and I will compare these values and set value higher one to DB. Here is my code as follows but I cant take value:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("Datas");
myRefchild=myRef.child(uuidstring).child("TimerMode").child("BestScore");

myRefchild.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            //PrevBestValue=Integer.parseInt(dataSnapshot.getValue(String.class));
            try {
                PrevBestValue=Integer.parseInt(dataSnapshot.getValue(String.class));
            }catch (Exception e){
                Log.d("DBhata",e.toString());
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {}
    });

if (PrevBestValue<TotalScore){
    myRefchild.setValue(Integer.toString(TotalScore));
}  
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

You cannot simply get use the value of PrevBestValue outside the onDataChange() method. Basically, you're trying to use a value synchronously in an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.

Firebase APIs are asynchronous, meaning that onDataChange() method returns immediately after it's invoked, and the callback from the Task object it returns, will be called some time later. There are no guarantees about how long it will take. It may take from a few hundred milliseconds to a few seconds before that data is available. Because that method returns immediately, the value of your PrevBestValue variable you're trying to use it outside the callback, will not have been populated yet.

A quick solve for this problem would be to move the following lines of code:

if (PrevBestValue<TotalScore){
    myRefchild.setValue(Integer.toString(TotalScore));
}

Inside the onDataChange() method, right after the following line of code:

PrevBestValue=Integer.parseInt(dataSnapshot.getValue(String.class));

If you want to use it outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

However, I showed you the above solutions to have an understanding regarding asynchronous APIs but this is not the way you should update a score field in a multiuser environment. To have consistent data, I recommend you see my answer from this post, where I have explained how to update a score field using Firebase Transactions.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193