java - 无论活动的生命周期如何,如何确保完成更新 firebase 数据库的过程
问题描述
我的应用程序有一个显示新闻文章的活动,它有一个书签 ImageButton。单击时,调用如下所示的方法
public void onBookmarkClick(View view){
if (isBookmarked){
bookmarkedDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
Article articleValue = snapshot.getValue(Article.class);
String id = snapshot.getKey();
if (article.equals(articleValue)){
bookmarkedDatabase.child(id).removeValue();
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}else {
String id = bookmarkedDatabase.push().getKey();
bookmarkedDatabase.child(id).setValue(article);
}
isBookmarked = !isBookmarked;
setupBookmarkIcon();
}
但是当我在单击书签按钮后立即旋转屏幕或按返回按钮时,文章不会添加到书签中。
即使活动被破坏,我如何确保从/向 Firebase 数据库读取和写入的过程是完整的。
解决方案
您可以使用完整的侦听器来了解您的更新是否成功。来自firebase文档
Add a Completion Callback
If you want to know when your data has been committed, you can add a completion listener.
Both setValue() and updateChildren() take an optional completion
listener that is called when
the write has been successfully committed to the database.
If the call was unsuccessful, the listener is passed an error object indicating why the failure occurred
或者我建议使用 viewModel 类并从那里进行更新。
推荐阅读
- sql - 将数组放入 WHERE IN 子句 Ruby on Rails
- sql - 如何获得每个岛屿的第一排和最后一排?
- javascript - 如何在数组Javascript上查找字符串的索引
- javascript - 当我修改 img src 时,jsPDF 不打印 img
- python - 如何在python中使用地理编码器获取邮政编码,提供地理坐标
- express - 将异步等待与猫鼬和快递一起使用
- flutter - 是否可以创建一个函数来使用 FutureBuilder,而不必重复代码?
- javascript - 反应日期选择器过滤日期问题
- c - `typedef` 在这种情况下是什么意思
- sql - SQL日期格式查询