android - 使用 Android Studio 从 firestore 获取数组值
问题描述
我正在尝试使用 getCurrentData 方法从我的 firestore 数据库中获取“comments”数组的所有元素,但经过一些调试后我发现我得到的只是空数组而不是“comments”元素(“Hello”、“World”)。
我的 DocumentReference 定义为:
commentReference = db.collection("Users").document(currentUser);
我认为正确定义了commentReference,但我仍然无法获得评论数组值。
此外,在调试时跳过了 getCurrentData 方法内部的 onComplete 方法。
我需要获取所有元素才能在回收站视图自定义布局中显示它们。
public class ListActivity extends AppCompatActivity {
ArrayList<String> currentComments;
DocumentReference commentReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
//TODO : Show user's comments
db = FirebaseFirestore.getInstance();
currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
commentReference = db.collection("Users").document(currentUser);
//HERE IS THE ARRAY & getCurrentData()
currentComments = new ArrayList<>();
getCurrentData();
//currentComments Still EMPTY!
}
public void getCurrentData() {
commentReference.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
currentComments = (ArrayList<String>) document.get("comments");
//Iterate through the list to get the desired values
}
}
}
}); //currentComments still empty, onComplete method is skipped!
}
解决方案
尝试使用 QueryDocumentSnaphot 访问您存储在 firestore 数据库中的数据。我能为你找到一个教程https://codinginflow.com/tutorials/android/cloud-firestore/part-16-arrays
推荐阅读
- python - 如何修改不存在的列表的位置?
- java - 使用 CloudSolrClient 连接到 solrcloud 时出错
- react-native - 如何从 react-native-gesture-handler 设置 PanGestureHandler 中的初始偏移量?
- c# - 提示用户通过多个类输入数据信息
- ios - 将 UIView.isAccessibleElement 设置为 true 会禁用在画外音模式下单击子视图
- html - 我正在尝试在新选项卡中打开此链接,以便用户不必离开我的网站,但它不适用于 _blank
- sqlite - 如何将 Future 数据转换为双精度列表?
- java - 恢复旧项目但清单合并失败?
- python-3.x - 为什么我不能从 python 脚本打开 EXE 文件?
- android - Facebook Android SDK 5.4.0 更新后导致 ANR