java - 在 Firebase Android 中将带有子项的值转换为 Java 对象

标签 java android firebase firebase-realtime-database

我已阅读question关于如何在 Firebase 中获取其子项的值(value)。

enter image description here

现在我想将该值转换为 Java 对象。我可以这样做吗?如果可以,我该如何实现?

最佳答案

Now I want to convert that value into a Java object. Can I do that?

当然可以!其实我也回答过这个问题。所以要解决这个问题,首先你需要创建两个 POJO(模型)类:

class MailId {
    public String email, name;

    MailId() {}
}

class MailText {
    public String subject, title;

    MailText() {}
}

要获取该数据作为 MailIdMailText 类的对象,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference newRef = rootRef.child("new");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.child("mailID").getChildren()) {
            MailId mailId = ds.getValue(MailId.class);
            Log.d("TAG", mailId.email + " / " + mailId.name);
        }
        for(DataSnapshot ds : dataSnapshot.child("mailText").getChildren()) {
            MailText mailText = ds.getValue(MailText.class);
            Log.d("TAG", mailText.subject + " / " + mailText.title);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
newRef.addListenerForSingleValueEvent(valueEventListener);

关于java - 在 Firebase Android 中将带有子项的值转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506946/

相关文章:

java - Hibernate:删除的对象将通过级联重新保存

java - 如何使用条件、分离条件和子查询检索对象

android - ListView 具有按文本过滤图像和文本的功能

java - 使用 log4j2 记录 Spring 事务

Java Flux GroupedFlux count() 打印

java - 对 Android 应用程序进行逆向工程时,Smali 代码与 Java 源代码的对比

android - 如何在 2 秒后从服务器在 imageview 中更改图像?

android - Firebase FCM,同一个 firebase 项目中的多个应用程序

javascript - 将 Firestore 添加到现有 Firebase 项目时遇到问题

ios - Firebase 数据库结构的建议