【发布时间】:2021-07-28 09:51:03
【问题描述】:
我正在从 Firestore 中检索医院数据。我想将检索到的数据保持为整个片段的全局,但是从 addOnSuccessListner() 出来后 Map 将返回 null。
我已经在 onCreateView() 中声明了 Map
static Map<String, Map<String, String>> hospitals ;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
hospitals = new HashMap<>();
.......
.....
return root;
}
下面是我检索 HospitalData 的代码。
private void readHospitalData() {
CollectionReference collectionReference = fStore.collection("hospital Details");
collectionReference.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for(QueryDocumentSnapshot queryDocumentSnapshot: queryDocumentSnapshots){
Map<String, String> map = new HashMap<>();
map.put("h_name", queryDocumentSnapshot.getString("h_name"));
map.put("h_email", queryDocumentSnapshot.getString("h_email"));
map.put("h_phone", queryDocumentSnapshot.getString("h_phone"));
map.put("h_road", queryDocumentSnapshot.getString("h_road"));
map.put("h_area", queryDocumentSnapshot.getString("h_area"));
map.put("h_city", queryDocumentSnapshot.getString("h_city"));
map.put("h_state", queryDocumentSnapshot.getString("h_state"));
map.put("h_pincode", queryDocumentSnapshot.getString("h_pincode"));
hospitals.put(queryDocumentSnapshot.getId(), map);
}
Log.d("MAP-->" , hospitals.toString()); // display the Map
}
});
Log.d("MAP-->" , hospitals.toString()); // but here it will display null
}
【问题讨论】:
-
它不应该为空,除非你在
onCreateView之前调用readHospitalData。它将为空collectionReference.get()是一个异步调用,因此您只需将 Logs 放入onSuccess中。 -
您也可以查看 this。
标签: java android firebase google-cloud-firestore global-variables