我正在尝试将 DataSnapshot 值转换为对象。它工作正常,我相信 bean 构造函数(带参数)用于转换。我添加了一些代码行来执行一些操作,但是我添加的代码行从未被执行。示例 bean 类:
@IgnoreExtraProperties
public class DatabaseRecord {
private String firstName;
private String lastName;
private String fullName;
private DatabaseRecord() {
}
public DatabaseRecord(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
// following code not executing
this.fullName = firstName + lastName;
}
public String getFirstName() { return firstName; }
public String getLastName() { return lastName; }
public String getFullName() { return fullName; }
}
数据获取执行代码:
DatabaseReference databaseReference = database.getReference("/user/user1");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
DatabaseRecord record = dataSnapshot.getValue(DatabaseRecord.class);
Log.d(TAG, record.getFirstName()+":"+record.getLastName()+":"+record.getFullName());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
输出:
Satish:Pandey:null
Google 文档显示了用于设置属性的参数化构造函数,如果是这种情况,为什么我的代码不执行?
Google 转换完成后如何在同一个 bean 对象中附加我的代码?
最佳答案
在您的情况下,被调用的构造函数是无参数的,因为您正在使用 getValue()
从数据库中读取数据,这是映射 DataSnapshot
中的值所必需的。根据文档,要将 DataSnapshot
数据获取到自定义 Java 类中,您必须遵循以下规则:
The class must have a default constructor that takes no arguments
The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized.
如果您想设置属性 fullName
的值,您可以使用相同的 getFullName()
方法来完成此操作。像这样的事情:
public String getFullName() {
if(fullName == null){// it will be null the first time assuming the value doesn't exist in the database.
fullName = getFirstName() + getLastName();
}
return fullName;
}
关于android - Firebase 实时数据库 DataSnapshot 值到对象的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46587667/