gpt4 book ai didi

java - 将类(class)保存到 firebase

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:51:31 26 4
gpt4 key购买 nike

我的类是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;

}

这个类只有静态属性。不需要实例化。

在我的 ma​​inActivity.class 中,我想设置类的值,然后存储这个 firebase 数据库。这是我的 ma​​inActivity.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<String, Class<CreditcardinfoOjbect>> hashMap = new HashMap<>();
hashMap.put("card", CreditcardinfoOjbect.class);
ref.setValue("card",hashMap );

不幸的是,这是行不通的。如何在 Firebase 中存储类的当前值?

最佳答案

首先,您需要向 POJO 类添加 Firebase 所需的无参数构造函数以及每个字段的公共(public) setter 和公共(public) 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;}
}

请注意,您不需要静态字段。另请注意,我将您的所有字段设置为私有(private)。在这种情况下,不需要 setter 和 getter。

现在,要设置 POJO 类的值,您需要创建 CreditCardInfoObject 类的新实例并使用公共(public) 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);

关于java - 将类(class)保存到 firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45410314/

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