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

Android中Firebase get请求监听器始终不触发问题求助

Firestore Get请求监听器不触发的排查方案

已在Firebase Firestore的get请求中设置OnSuccessListener、OnFailureListener和OnCanceledListener,Firestore权限已设为全开放(调试用),用户身份验证已成功,但所有监听器始终不触发。相关代码如下:

Globals.db = FirebaseFirestore.getInstance();
DocumentReference user = null;
if (!Globals.testMode)
    user = Globals.db.collection("users").document(email.getText().toString());
else 
    user = Globals.db.collection("users").document(Globals.testEmail);
System.out.println("DebugMode01: " + Globals.fireAuth.toString());

if (Globals.fireAuth.getCurrentUser() != null){
    System.out.printf("The user instance is correct.");
}

user.get().addOnSuccessListener(userDocument -> {
    Globals.initUser((String)userDocument.get("email"),(String)userDocument.get("fname"), (String)userDocument.get("lname"));
    warning.setVisibility(View.INVISIBLE);
    Globals.endLoad();
    Toast.makeText(LoginActivity.this, "Login success!", Toast.LENGTH_LONG).show();
}).addOnFailureListener( x -> {
    Globals.endLoad();
    warning.setText("Invalid error instance with the server.");
    warning.setVisibility(View.VISIBLE);
}).addOnCanceledListener(() -> {
    warning.setText("This process was cancelled.");
    Globals.endLoad();
    warning.setVisibility(View.VISIBLE);
});

可能的原因及解决方法

  • 主线程阻塞
    Firestore回调在主线程执行,如果当前主线程被耗时操作(同步网络请求、大量计算等)阻塞,回调会被挂起。检查请求前后是否有阻塞主线程的代码,比如Globals.startLoad()是否包含同步等待逻辑。

  • DocumentReference初始化异常
    检查Globals.testMode值、email.getText().toString()和Globals.testEmail是否为有效字符串(比如空字符串、含非法路径字符)。添加日志打印文档路径确认:

    System.out.println("Target document path: " + user.getPath());
    

    无效路径会导致请求无法正常发起。

  • Firestore实例问题
    确保Globals.db是全局唯一实例,建议在Application类的onCreate方法中初始化,避免重复创建:

    public class MyApp extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            FirebaseFirestore.setLoggingEnabled(true);
            Globals.db = FirebaseFirestore.getInstance();
        }
    }
    

    开启Firestore日志(FirebaseFirestore.setLoggingEnabled(true)),可查看底层请求的发起、响应细节,定位是否存在请求异常。

  • 网络或离线缓存问题
    Firestore请求需要网络连接(开启离线持久化时,会优先读缓存,缓存不存在也会触发失败回调)。检查设备网络状态,测试是否能正常访问Firebase控制台。

  • 生命周期或取消逻辑干扰
    如果请求在Activity/Fragment中发起,确保组件未被销毁,可绑定生命周期避免回调丢失:

    user.get().addOnSuccessListener(LoginActivity.this, userDocument -> {
        // 原有逻辑
    });
    

    同时检查是否有代码调用了请求的cancel()方法,导致请求被主动取消。

  • 依赖版本不兼容
    确认项目中firebase-firestore、firebase-auth等相关依赖版本一致,建议使用最新稳定版,避免版本冲突导致的回调异常。

内容的提问来源于stack exchange,提问作者ruff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 08:27:43