0

Im trying to set value to a global variable in OnDataChange() and share it to other methods but it turns out that it always gives me a null

String mCurrentState; //global variable

     mUsersDatabase.addValueEventListener(new ValueEventListener() {

             @Override
             public void onDataChange(DataSnapshot dataSnapshot) {
                  mCurrentState = "normal";
             }
             @Override
             public void onCancelled(DatabaseError databaseError) {

             }
       }

Is there any way to set a global variable inside a onDataChange()

  • in what way is it a global variable? Does not look very global to me – luk2302 Apr 14 '18 at 14:43
  • If it's null, it's probably that you're trying to read the variable **before** it's been set **asynchronously** by the onDataChange method. It might also be a visibility issue between threads. But with the code you posted, we can't know. – JB Nizet Apr 14 '18 at 14:43
  • Possible duplicate of [How to return dataSnapshot value as a result of a method?](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method) – Alex Mamo Apr 23 '18 at 17:01
  • No, there is not. Please see the duplicate to see why is this happening and how you can solve this. – Alex Mamo Apr 23 '18 at 17:01

0 Answers0