【问题标题】:Updating Firebase Database Data with android使用 android 更新 Firebase 数据库数据
【发布时间】:2019-04-05 08:31:40
【问题描述】:

我正在使用这种方法将数据存储在我的 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 对象并再次使用存储的 ID 执行 ref.child(id).setValue(newSub);,数据会是更新 ?还是有其他方法可以做到这一点?

【问题讨论】:

    标签: android firebase firebase-realtime-database


    【解决方案1】:

    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);
    }
    

    【讨论】:

    • 什么是地图?
    • 谢谢。我发现了别的东西。
    • HashMap 用于存储键值对。Key 是孩子,value 是您要在该孩子下更新的数据。
    • 那么与其为类模型创建映射,为什么直接使用类不是更好
    • 你的选择
    【解决方案2】:

    好的,所以我尝试了这个,它完美地工作,就像我预期的那样。我不需要使用地图或任何东西。更新数据的最简单方法。

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

    所以基本上,我在这里创建了具有所需数据的对象,并将其推送回我在 firebase 数据库中创建节点时使用的同一 ID,因此它使用新值更新同一节点。

    【讨论】:

      猜你喜欢
      • 2019-02-18
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多