如何从Firebase android getValue()检索正确的子类型 [英] How to retrieve correct subtype from firebase android getValue()

查看:38
本文介绍了如何从Firebase android getValue()检索正确的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想不出一个更好的例子来说明我的观点,所以如果我的例子有错误,请告诉我.但希望这个例子能使我明白.

Hi all I can't think of a better example to illustrate my point so do let me know If my example has some errors. But hopefully this example will get my point through.

class A {
    String CATEGORY = "A";

    public String getCATEGORY() {
        return CATEGORY;
    }
}

class B extends A {
    String CATEGORY = "B";


    @Override
    public String getCATEGORY() {
        return CATEGORY;
    }
}


class C extends A {
    String CATEGORY = "C";

    @Override
    public String getCATEGORY() {
        return CATEGORY;
    }
}

public class MyClass {
    private List<A> array = Arrays.asList(new A(), new B(), new C());

    public MyClass() {}

}

现在,例如,如果我使用setValue将MyClass上载到firebase上,firebase将向我显示类A,B和C的属性.但是,当我从firebase读取数据并像getValue(MyClass.class)这样调用时,列表它返回我都是A类型的,并且不保留子类.有没有解决方法可以让Firebase保留上传的类类型?

Now if I upload MyClass onto firebase using setValue for example, firebase will show me the properties of class A, B and C. However, when I read the data from firebase and call sth like getValue(MyClass.class) the List it returns me are all of type A and the subclasses are not preserved. Is there a workaround to allow firebase to preserve the class types uploaded?

推荐答案

如果您使用Firebase的默认序列化程序,它只会将所有公共属性和字段写入数据库.假设您存储了每个类的单个实例,那么它将是:

If you use Firebase's default serializer, it simply writes all public properties and fields to the database. Say that you store a single instance of each class, it'd be:

-L1234567890: {
  cATEGORY: "A"
},
-L1234567891: {
  cATEGORY: "B"
},
-L1234567892: {
  cATEGORY: "C"
},

数据库中没有足够的知识来使SDK重新创建正确的子类.虽然您和我可以看到 cATEGORY 值与类名匹配,但是Firebase SDK却没有这样的知识.

There won't be enough knowledge in the database for the SDK to reinflate the correct sub-class. While you and I can see that the cATEGORY value matches the class name, the Firebase SDK has no such knowledge.

不过,为上述数据编写自己的自定义反序列化器并不难,使用上面的值作为 DataSnapshot 并重新填充正确的类和值.

It won't be too hard to write your own custom deserializer for this data though, taking a DataSnapshot with the values above and reinflating the correct class and values.

您还可以进行混合:直接检测类的类型,然后告诉Firebase要读取的类:

You could also do a hybrid: detect the class type directly, and then tell Firebase what class to read:

String cat = snapshot.child("cATEGORY").getValue(String.class)
Class clazz = "C".equals(cat) ? C.class : "B".equals(cat) ? B.class : A.clas;
A object = snapshot.getValue(clazz);

这篇关于如何从Firebase android getValue()检索正确的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆