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;
}
我有方法在外面检查黄金但是如何在方法onDataChange
中返回false。感谢。
答案 0 :(得分:1)
Firebase数据库是异步的,它的流量超出了我们通常执行的常规流程。 In this post,我试图解释(仅供参考)
在这种情况下,你会做这样的事情,对吧?
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
}
但如果我们知道它是异步的,它应该是这样的:
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
}
}
...
});
}
或者,如果你像我一样想要一些整洁的东西:
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
}
}
需要时间熟悉这一点,但这是值得的。希望这有帮助