gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:58:28 25 4
gpt4 key购买 nike

我在文档字段中存储了一组自定义类,例如“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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com