android - 如何获取在 Firestore 中存储为 FieldValue 的数组中的特定元素

标签 android arrays google-cloud-firestore

我在文档字段中存储了一组自定义类,例如“Patient”。它存储正确,但现在当我尝试将它下载到 android studio 时,它在日志语句中看起来像这样:-

[{"appointmentnumber"=26, "name"="Neeraj Aggarwal", "phonenumber"="+917988081391"}, {appointmentnumber=27, name=Aaskah Sharma, phonenumber=+917988081391}, {appointmentnumber=28, name=Mohit sskm, phonenumber=+917988081391}]

它看起来像一个数组,但我无法在其上应用数组的任何属性。就像当我尝试获取此数组的第一个元素时,如 ArrayName[0] 然后它显示如下错误:

java.lang.ClassCastException: java.util.HashMap 无法转换为 com.example.reception.Patient (接收我的项目名称和你知道的患者是自定义类名称)

我也不知道如何获取存储为字段值的数组中特定元素的值。比如我们可以通过documentsnapshot.get("Fieldname.Keyname")提取map的特定值,有没有类似这样的方法获取数组中特定位置的元素。

最佳答案

Firebase 解决了我的问题。他们的回答是这样的:-

Firebase Support

10:56 AM (29 minutes ago)

对我来说

Hello Neeraj,

I'm Ian, here to answer any questions you may have when it comes to using Firestore for Android.

If you use the snapshot.get() method on a field containing an array of objects, the Android SDK will return that value as a Java List of HashMap objects. There's currently no way to override this behavior, so you may need to manually get each key-value pair and set the value to a Patient object.

With that said, it is possible to convert the entirety of the document snapshot into a Java object in one go, without needing to use a method like snapshot.get(). Assuming your Doctor class looks something like this:

public class Doctor {
    private List<Patient> patients;
    //other variables

    //Constructor must be empty
    public Doctor() {}

    public List<Patient> getPatients() {
        return patients;
    }

    public void setPatients(List<Patient> patients) {
        this.patients = patients;
    }

You can convert your document snapshot into the Doctor object with just one line of code:

Doctor doctor = snapshot.toObject(Doctor.class);

From there, you can get your Java List of patients, and then perform your computation on the patient data as intended.

所以所有的诀窍就是使用 toObject 方法。

关于android - 如何获取在 Firestore 中存储为 FieldValue 的数组中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58722356/

相关文章:

javascript - 参数结果隐式具有任何类型

android - 工具 :replace="android:appComponentFactory Error

android - 以 AMR 文件格式录制音频

android - 使用asynctask调用android中的函数

java - 访问 JTextAreas 数组时出现 NullPointerException

php - 循环内的多维数组合并操作

arrays - Ruby 遍历数组获取方法名

firebase - 我是否正确使用Firestore索引?

database - native 模式下的 Firestore DB 文档写入限制

Android 方向和屏幕尺寸问题