android - 使用 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,数据会更新吗?还是有其他方法可以做到这一点?
解决方案
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);
}
推荐阅读
- c# - 为什么我的 HttpPost 方法没有从我的 Asp.Net Core Razor 页面触发?
- jsonschema - Json Schema对外部字段的依赖
- express - 无法使用 Twilio 试用帐户接收 SMS 消息
- r - 数组中的错误......“不允许负长度向量”
- r - igraph 有“has_path”功能吗?
- javascript - 为什么我的浏览器没有使用 pupeeteer 脚本定位到此页面?
- sql - 如何使用 SQL 在表中进行测试训练拆分?
- playwright - 带有投影的剧作家选择器?
- python - 将数据集(CONLL 格式)拆分为开发、训练和测试
- python - python sqlite 查询的复杂性是否会严重影响 fetchall() 时间?