我的应用程序必须在 ListView 上显示名称列表。这些名称按以下方式存储在 Cloud Firestore 中:
集合:用户 - 文档:按用户 UID 组织 - 字段:名称(我必须注意,每个用户还有其他字段,但我需要专门检索名称字段)
为了实现此目的,我有一个第一个列表,用于检索所有文档或用户 UID。然后,在 for 循环中使用第一个列表来检索 users 集合中每个用户的名称。
但是,由于 Firebase 异步检索数据,某些名称通常会丢失,并且最终会以无序的方式显示(与从第一个列表传递 uid 的顺序不一致)。
如果有人能够告诉我如何让 Firebase 在继续 for 循环之前等待数据被检索,我将不胜感激!
下面是我的一些代码,可以让您更好地了解我在做什么。
代码的第一部分,成功检索所有文档(uid)并将它们放在列表中
subTopicsDatabase.collection("schoolTopics").document(docKey).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()){
DocumentSnapshot document = task.getResult();
if (document.exists()) {
List<String> list = new ArrayList<>();
Map<String, Object> map = document.getData();
if (map != null) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
list.add(entry.getValue().toString());
}
}
}});
代码的第二部分由于 Firebase 的异步行为而不起作用。
for (int i = 0; i<list.size(); i++) {
String uid = list.get(i);
Toast.makeText(TutorsListActivity.this, uid, Toast.LENGTH_LONG).show();
subTopicsDatabase.collection("users").document(uid).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
String stName = documentSnapshot.getString("name");
ArrayAdapter<String> adapter = new ArrayAdapter<>(TutorsListActivity.this, R.layout.item_subtopic, testList);
adapter.notifyDataSetChanged();
sListView2.setAdapter(adapter);
}
}
});
}
最佳答案
您需要存储元素,并且在 for 循环的最后中,您必须显示名称列表。
正如您所说,您将获得所有 UID 的列表,现在您希望他们的名字出现在列表中。我已更新您的代码以使其正常工作。
// Create a Hashmap Object which has Key as UID and Name as Key
HashMap<String,String> hashMap = new HashMap<>();
for (int i = 0; i<list.size(); i++) {
final String uid = list.get(i);
Toast.makeText(TutorsListActivity.this, uid, Toast.LENGTH_LONG).show();
subTopicsDatabase.collection("users").document(uid).get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
//Store Your UID and Name in Hashmap
String stName = documentSnapshot.getString("name");
hashMap.put(uid,stName);
}
//Check if it is last index of array then show the names list
if(i==list.size()-1){
showListInAdapter(hashMap);
}
}
});
}
private void showListInAdapter(HashMap<String,String> hashMap) {
//now convert your hashmap into a list of name and get Your Names List and show in Adapter
ArrayList<String> listOfNames = new ArrayList<>(hashMap.keySet());
//Set list to Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(TutorsListActivity.this, R.layout.item_subtopic, listOfNames);
sListView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
关于java - 有没有办法让我的应用程序等待从 Firebase 检索数据,然后再继续代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57116491/