java – 将类保存到firebase

前端之家收集整理的这篇文章主要介绍了java – 将类保存到firebase前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我的班级是CredicardinfoObject.class

public class CreditcardinfoOjbect implements Serializable {
    private static final long serialVersionUID = 1L;

    public static String title;
    public static String startTime;
    public static String endTime;
    public static String day;

}

这个类只有静态的特性.没有实例化需要.

在我的mainActivity.class中,我想设置类的值,然后存储此firebase数据库.这是我的mainActivity.class.

    CreditcardinfoOjbect.title = "foo";
    CreditcardinfoOjbect.startTime = "bar";
    CreditcardinfoOjbect.day = "1";
    CreditcardinfoOjbect.endTime = "2";

    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    String uid = "";
    FirebaseAuth auth = FirebaseAuth.getInstance();
    FirebaseUser user = auth.getCurrentUser();
    if (user != null) {
        uid = user.getUid();
    }
    DatabaseReference ref = database.getReference("users").child(uid).child("account").child("creditcards");

    HashMap

不幸的是,这不起作用.如何在Firebase中存储类的当前值?

最佳答案
首先,您需要添加到您的pojo类,Firebase需要的无参数构造,以及每个字段的公共setter和公共getter,如下所示:

public class CreditCardInfoObject implements Serializable {
    private String title;
    privat eString startTime;
    private String endTime;
    private String day;

    public CreditCardInfoObject() {}

    public String getTitle() {return title;}
    public void setTitle(String title) {this.title = title;}

    public String getStartTime() {return startTime;}
    public void setStartTime(String startTime) {this.startTime = startTime;}

    public String getEndTime() {return endTime;}
    public void setEndTime(String endTime) {this.endTime = endTime;}

    public String getDay() {return day;}
    public void setDay(String day) {this.day = day;}
}

请注意,您不需要静态字段.另请注意,我将您的所有字段设置为私有.将这些字段设置为公共字段是一种非常糟糕的做法.

现在,要设置pojo类的值,需要创建CreditCardInfoObject类的新对象并使用公共setter.拥有此新对象后,您可以将其保存到Firebase数据库,如下所示:

CreditcardinfoOjbect obj = new CreditcardinfoOjbect();
obj.setTitle("foo");
obj.setStartTime("bar");
obj.setEndTime("1");
obj.setDay("2");

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uid = "";
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
    uid = user.getUid();
}
DatabaseReference ref = rootRef.child("users").child(uid).child("account").child("creditcards");
ref.setValue(obj);

猜你在找的Android相关文章