You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Firebase登出后重登崩溃:setPersistenceEnabled调用时机异常

问题解决:Firebase登出后重新登录崩溃

错误原因

报错Calls to setPersistenceEnabled() must be made before any other usage of FirebaseDatabase instance的核心问题是:setPersistenceEnabled(true)只能被调用一次,且必须在第一次获取FirebaseDatabase实例之前执行。

你的代码里把这个调用放在MainActivity的onCreate中,每次登出后重新登录进入MainActivity时,都会再次执行这个方法。而此时FirebaseDatabase实例已经在之前的会话中被初始化过,再次调用setPersistenceEnabled就会触发异常。

解决方案

把setPersistenceEnabled(true)移到自定义Application类中,因为Application的onCreate方法在整个App生命周期内只会执行一次,能保证在所有Activity初始化前完成Firebase持久化配置。

步骤1:创建自定义Application类

新建一个类继承自Application,在onCreate中初始化Firebase持久化:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // 这里是设置持久化的正确位置,确保全局只调用一次
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }
}

步骤2:在Manifest中注册自定义Application

修改AndroidManifest.xml,在<application>标签中指定自定义Application:

<application
    android:name=".MyApp" <!-- 新增这行 -->
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.YourAppName">
    <!-- 其他Activity配置 -->
</application>

步骤3:修改MainActivity代码

移除MainActivity中onCreate里的setPersistenceEnabled调用:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Objects.requireNonNull(getSupportActionBar());

    CheckLogin();

    // 删掉这行:FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    databaseReference = FirebaseDatabase.getInstance().getReference();

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    tasksArrayList = new ArrayList<>();

    ReadData();
}

这样修改后,无论你登出多少次再重新登录,setPersistenceEnabled只会在App启动时执行一次,彻底避免重复调用的问题。

内容的提问来源于stack exchange,提问作者Foca O Tank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:50:26