首页 > 解决方案 > 无论活动的生命周期如何,如何确保完成更新 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 数据库读取和写入的过程是完整的。

标签: javaandroidfirebase-realtime-database

解决方案


您可以使用完整的侦听器来了解您的更新是否成功。来自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 类并从那里进行更新。

视图模型


推荐阅读