【发布时间】:2016-07-19 10:59:45
【问题描述】:
我目前正在开发一个 android 应用程序,我在其中使用 firebase 作为数据库,但是当在 onDataChange 方法中获取变量并将它们分配给全局变量时,我得到了 null 变量,但是当我在 onDataChange 中调用这些变量时方法它们不为空。
public class PositionateMarkerTask extends AsyncTask {
public ArrayList<Location> arrayList= new ArrayList<>();
public void connect() {
//setting connexion parameter
final Firebase ref = new Firebase("https://test.firebaseio.com/test");
Query query = ref.orderByChild("longitude");
//get the data from the DB
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//checking if the user exist
if(dataSnapshot.exists()){
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
//get each user which has the target username
Location location =userSnapshot.getValue(Location.class);
arrayList.add(location);
//if the password is true , the data will be storaged in the sharedPreferences file and a Home activity will be launched
}
}
else{
System.out.println("not found");
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("problem ");
}
});
}
@Override
protected Object doInBackground(Object[] params) {
connect();
return null;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
System.out.println("the firs long is"+arrayList.get(0).getLongitude());
}
}
【问题讨论】:
-
你的全局变量在哪里
-
arrayList 是我的全局变量
-
是的...
onPostExecute不会等到您arrayList有项目。这就是为什么它是空的。 -
一般onpostexecute是在onbackground方法执行完之后才执行的,所以必须等待
-
不,从您的代码来看,它不会等待 ValueEventListener 方法。在完成附加 ValueEventListener 后直接调用 onPostExecute。 firebase 数据库也可以异步工作。
标签: android firebase firebase-realtime-database