【问题标题】:Firebase Firestore: Cannot call useEmulator() after instance has already been initializedFirebase Firestore:实例已初始化后无法调用 useEmulator()
【发布时间】:2021-02-26 08:24:05
【问题描述】:

我正在使用 Firebase Emulator Suite 来测试我的 Firebase Cloud Functions,然后再将它们部署到生产环境中。

探索this 方法以从我的 Andriod 设备触发可调用的 Firebase 云功能。

我的应用在运行时崩溃了。

错误:

java.lang.IllegalStateException: 实例初始化后无法调用 useEmulator()。

错误来源 - FirebaseFirestore.java

/**
   * Modifies this FirebaseDatabase instance to communicate with the Cloud Firestore emulator.
   *
   * <p>Note: Call this method before using the instance to do any database operations.
   *
   * @param host the emulator host (for example, 10.0.2.2)
   * @param port the emulator port (for example, 8080)
   */
  public void useEmulator(@NonNull String host, int port) {
    if (this.client != null) {
      throw new IllegalStateException(
          "Cannot call useEmulator() after instance has already been initialized.");
    }

    this.emulatorSettings = new EmulatedServiceSettings(host, port);
    this.settings = mergeEmulatorSettings(this.settings, this.emulatorSettings);
  }

Firestore 使用以下方法注入:(在我的项目中使用 Hilt)

@Provides
fun provideFirebaseFirestore(): FirebaseFirestore {

    val firebaseFirestoreSettings = FirebaseFirestoreSettings.Builder()
    firebaseFirestoreSettings.isPersistenceEnabled = false

    val firestore = FirebaseFirestore.getInstance()
    firestore.useEmulator("192.168.1.102", 8080)
    firestore.firestoreSettings = firebaseFirestoreSettings.build()

    return firestore
}

我怀疑useEmulator() 中的FirebaseFirestore.java 不是静态方法。
在创建 Firebase Firestore 实例之前如何调用它?

【问题讨论】:

  • 您的应用程序中的其他任何地方是否有任何其他代码调用FirebaseFirestore.getInstance()
  • @DougStevenson,不,依赖在 @Module @InstallIn(ApplicationComponent::class) class FirebaseModule {....}
  • 目前是单模块应用。
  • 如果你有一个精简的、绝对最小的应用程序,它只使用你这里的代码生成这个错误,我建议提交一个错误报告,并解释如何重现它。 github.com/firebase/firebase-android-sdk

标签: android firebase google-cloud-firestore google-cloud-functions firebase-tools


【解决方案1】:

这可能是因为 Firebase 状态在测试之间保持不变。然后针对同一个 firebase 应用程序实例调用 useEmulator 两次,从而引发错误。至少,这是我在测试期间发生的事情。

检查 firestore 实例中嵌套的“主机”属性的方法——描述为 in this answer——对我有用。

【讨论】:

    【解决方案2】:

    我有同样的问题,我解决它的方法将 firestore.useEmulator("192.168.1.102", 8080) 包装在这样的 try catch 块中

        try {
                firestore.useEmulator("192.168.1.102", 8080)
            } catch (e: IllegalStateException) {
    
            }
    

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      相关资源
      最近更新 更多