首页 > 解决方案 > 使用 android 更新 Firebase 数据库数据

问题描述

我正在使用这种方法将数据存储在我的 firebase 数据库中:

首先,我将所有数据存储在一个名为 SubjectDataModel 的模型类中,然后我从 firebase 数据库中获取推送键。

然后我为那个特定的键设置值。

这是我的代码:

主题数据模型:

public class SubjectDataModel {

    public String id;
    public String dbName;
    public String subName;
    public String tagline;
    public int preference;

    public SubjectDataModel()
    {

    }

    public SubjectDataModel(String id, String dbName, String subName, String tagline, int preference) {
        this.id = id;
        this.dbName = dbName;
        this.subName = subName;
        this.tagline = tagline;
        this.preference = preference;
    }
}

然后我使用以下代码将其推送到数据库,然后我还将密钥 ID 存储在本地。

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Data");
String id = ref.push().getKey();
SubjectDataModel newSub = new SubjectDataModel(id, txt_dbName, txt_subName, txt_tagline, txt_preference);
ref.child(id).setValue(newSub);

现在想象一下,稍后,我想更新这些数据,所以我存储了密钥 ID,所以我可以访问它,我还在本地编辑了所有其他数据,所以现在如果我用该数据创建一个 SubjectDataModel 对象再次ref.child(id).setValue(newSub);使用存储的 id,数据会更新吗?还是有其他方法可以做到这一点?

标签: androidfirebasefirebase-realtime-database

解决方案


updateChildren() 是您正在寻找的方法,请参阅此文档Firebase Read and Write Data on Android

这是文档中的一个示例...

private void writeNewPost(String userId, String username, String title, String body) {
    // Create new post at /user-posts/$userid/$postid and at
    // /posts/$postid simultaneously
    String key = mDatabase.child("posts").push().getKey();
    Post post = new Post(userId, username, title, body);
    Map<String, Object> postValues = post.toMap();

    Map<String, Object> childUpdates = new HashMap<>();
    childUpdates.put("/posts/" + key, postValues);
    childUpdates.put("/user-posts/" + userId + "/" + key, postValues);

    mDatabase.updateChildren(childUpdates);
}

推荐阅读