2
public boolean checkGold(final int gold){
    mRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue(String.class);
            goldparse = Integer.parseInt(value);
            if (gold > goldparse){
                /*Return*/
            }
        }
        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    });
    return false;
}

I have method to check gold in outside but how to return false in method onDataChange. Thanks.

koceeng
  • 2,169
  • 3
  • 16
  • 37

1 Answers1

1

Firebase Database is asyncronous, and its flow is outside the regular flow that we usually do. In this post, I tried to explain that (just for information)

And in this case, you do something like this, right?

boolean iWantValue = checkGold(10);
if (iWantValue) {
    // do someting
} else {
    // do something else
}
...
public boolean checkGold(final int gold) {
    ... // content here are still the same as mentioned in question
}

But if we know it is asyncronous, it should be like this:

int currentGold = 0; // place gold here so it can be accessed anywhere
...
// wherever you want to check gold, type this
currentGold = 10; // update this value first, right?
checkGold();
...
public void checkGold() {
    mRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String value = dataSnapshot.getValue(String.class);
            goldparse = Integer.parseInt(value);
            if (currentGold > goldparse){
                // do something
            } else {
                // do something here
            }
        }
        ...
    });
}

Or if you are like me who want something tidy:

public void checkGold() {
    mRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            doSomethingOrNot(Integer.parseInt(dataSnapshot.getValue(String.class)));
        }
        ...
    });
}

private void doSomethingOrNot(int goldparse) {
    if (currentGold > goldparse){
        // do something
    } else {
        // do something here
    }
}

It needs time to be familiar with this, but it's worth it. Hope this helps

Community
  • 1
  • 1
koceeng
  • 2,169
  • 3
  • 16
  • 37