首页 > 解决方案 > 使用 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!
    }

标签: androidfirebasegoogle-cloud-firestore

解决方案


尝试使用 QueryDocumentSnaphot 访问您存储在 firestore 数据库中的数据。我能为你找到一个教程https://codinginflow.com/tutorials/android/cloud-firestore/part-16-arrays


推荐阅读