Home » Android » How to set global var from onDataChange function [duplicate]

How to set global var from onDataChange function [duplicate]

Posted by: admin November 1, 2017 Leave a comment


This question already has an answer here:


The code inside of the firebase listener is a callback, it will be called at some point in the future but it is not specified when that will happen.

So what happens is:

  1. You call ref2.addListenerForSingleValueEvent(..)
  2. You execute Log.d("ID YYYYYYYY" , gameIDperm);, at this point the variable has not been changed yet.
  3. Firebase invokes onDataChange(..) at a later date, changing the variable.
  4. You execute Log.d("ID XXXX" , gameIDperm);

In such an asynchronous execution you cannot rely on the order of the code to tell you when things get executed.

In addition you are using the variable gameIDperm to look up a child of the firebase reference, then rewriting that variable with the contents. This is probably not correct.