fbm*_*tma 3 android firebase firebase-realtime-database
我正在开发一个Android应用程序,其中我使用firebase作为数据库,但是当在onDataChange方法中获取变量并将它们分配给全局变量时,我得到了空变量,但是当我在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());
}
}
Run Code Online (Sandbox Code Playgroud)
欢迎使用异步编程,这会扰乱你一直认为是真实的一切.:-)
Firebase会在后台自动检索/同步数据库.工作发生在一个单独的线程上,所以你不需要和AsyncTask.但不幸的是,这也意味着你不能等待数据.
我通常建议您将代码从"首先执行A,然后再运行到B"重新编写为"每当我们获得A,我们使用它执行B"时.
在您的情况下,您希望获取数据,然后打印第一个项目的经度.重新设计:无论何时收到数据,打印第一项的经度.
Query query = ref.orderByChild("longitude");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
Location location =userSnapshot.getValue(Location.class);
arrayList.add(location);
}
System.out.println("the first long is"+arrayList.get(0).getLongitude()); }
else{
System.out.println("not found");
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("problem ");
}
});
Run Code Online (Sandbox Code Playgroud)
这里有几点需要注意:
如果您只对第一项感兴趣,可以将查询限制为一项:query = ref.orderByChild("longitude").limitToFirst(1).这将检索更少的数据.
我推荐使用addValueEventListener()而不是addListenerForSingleValueEvent().前者将保持同步数据.这意味着如果您插入/更改列表中项目的经度,您的代码将自动重新触发并打印(可能)新的第一项.
| 归档时间: |
|
| 查看次数: |
5057 次 |
| 最近记录: |