如何解决这个Android Studio Firebase问题? [英] How can I solve this Android Studio Firebase problem?
问题描述
我正在尝试将数据从Firebase获取到bilgiler变量.但是我一直都出错.我该如何解决?
I am trying to get data from Firebase to bilgiler variable. But I get error all the time. How can I solve this?
Map<String, String> bilgiler = new HashMap<>();
db.collection("tarihBilgi")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
//Log.d("TAG", document.getId() + " => " + document.getData());
bilgiler.put("asdf", document.getData().toString());
}
} else {
Log.w("TAG", "Error getting documents.", task.getException());
}
}
});
Log.i("asdfads",(bilgiler.get("asdf")));
推荐答案
数据是从Firebase异步加载的.现在,您的 Log.i("asdfads",(bilgiler.get("asdf")));
在 bilgiler.put("asdf",document.getData()之前运行.toString())
运行,这说明了为什么看不到数据库中的值.
Data is loaded from Firebase asynchronously. Right now your Log.i("asdfads",(bilgiler.get("asdf")));
is run before bilgiler.put("asdf", document.getData().toString())
runs, which explains why you don't see the value from the database.
任何需要数据库中数据的代码,都必须在 onComplete
方法内部,或者从那里调用.所以:
Any code that needs data from the database, needs to be inside the onComplete
method, or be called from there. So:
db.collection("tarihBilgi")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
bilgiler.put("asdf", document.getData().toString());
Log.i("asdfads",(bilgiler.get("asdf")));
}
} else {
Log.w("TAG", "Error getting documents.", task.getException());
}
}
});
另请参阅:
- 如何检查Firestore中是否已经存在某些数据
- 用户在Firebase中登录
- 如何退货是由于方法而导致的DocumentSnapShot?
- 请等到Firestore数据检索以启动活动
- 执行线程的Firestore连接问题
这篇关于如何解决这个Android Studio Firebase问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!