android - Firebase 实时数据库 DataSnapshot 值到对象的转换

标签 android firebase firebase-realtime-database

我正在尝试将 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; }
}

Firebase 在线数据库流程: enter image description here

数据获取执行代码:

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

  1. Google 文档显示了用于设置属性的参数化构造函数,如果是这种情况,为什么我的代码不执行?

  2. 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/

相关文章:

javascript - Firebase 填充嵌套值

java - 在java中重置对象

java - camera2 输出到位图

android - Zxing处理后退按钮

firebase - 如何在Firebase云功能中获取客户端IP地址?

ios - 调用 `FIRApp.configure()` 时首次运行应用程序崩溃

javascript - AngularFire 获取 child 的数据

android - 带有搜索 View 的 Firebase Recycler 适配器

java - 访问 Firebase 中的 key

java - Java ArrayList 可以为空并且 indexOf 返回索引 0 吗?