在用 kotlin 编写的 Modulair Android 项目中初始化 Firebase 给出未初始化错误

Initializing Firebase in Modulair Android project written in kotlin gives not initialized error

我在尝试将 firebase 实施到用 kotlin 编写的模块化 android 项目时遇到困难。

我的结构是这样的:

然后在我的主要 activity oncreate 中调用 FirebaseApp.inialize(this)

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  FirebaseApp.initializeApp(this)
  setContentView(R.layout.activity_main)
  spotifyAuthDataViewModel = ViewModelProviders.of(this)
    .get(SpotifyAuthDataViewModel::class.java)

  val liveData = spotifyAuthDataViewModel.getAuthData()
  info { liveData.value!!.spotifyToken }
}

我的实时数据视图模型如下所示:

    class SpotifyAuthDataViewModel : ViewModel() {
  var authData: MutableLiveData<SpotifyAuthData> = MutableLiveData()
  private var mDatabase: DatabaseReference? = null

  fun getAuthData(): LiveData<SpotifyAuthData> {
    mDatabase = FirebaseDatabase.getInstance().reference
    FirebaseDatabase.getInstance()
          .getReference("/spotify_data")
          .addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onCancelled(p0: DatabaseError?) {
            }

            override fun onDataChange(dataSnapshot: DataSnapshot) {
              if (dataSnapshot.exists()) {
                var spotifyAuthData: SpotifyAuthData? =
                  dataSnapshot.getValue<SpotifyAuthData>(SpotifyAuthData::class.java)
                authData.postValue(spotifyAuthData)
              }
            }
          }
          )

    return authData

  }
}

但是当我尝试 运行 应用程序时,我收到了这条消息

  java.lang.RuntimeException: Unable to resume activity {com.jd.test.app/com.jd.test.feature.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.jd.test.app. Make sure to call FirebaseApp.initializeApp(Context) first.

我还尝试创建一个 class 扩展我的应用程序并调用 firebaseapp.initialize(this) 并将其添加到我的清单中,但我仍然遇到同样的错误。

清单:

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        package="com.jd.test.feature">
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <application android:name=".BaseApplication">
    <activity android:name=".MainActivity"
        android:theme="@style/AppTheme">
      <intent-filter android:order="1">
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT"/>

        <data
            android:host=""
            android:pathPrefix="/.*"
            android:scheme="https"/>
      </intent-filter>
      <intent-filter>
        <action android:name="android.intent.action.MAIN"/>

        <category android:name="android.intent.category.LAUNCHER"/>
      </intent-filter>
    </activity>
    <activity android:name=".spotify.views.SpotifyLogin"/>
  </application>


</manifest>

BaseApplication.kt:

class BaseApplication : Application() {
  override fun onCreate() {
    super.onCreate()
    FirebaseApp.initializeApp(this)
  }
}

我的特色gradle

    apply plugin: 'com.android.feature'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

apply plugin: 'kotlin-kapt'

android {
  compileSdkVersion 27
  defaultConfig {
    minSdkVersion 23
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
  }
  buildTypes {
    debug {
      useProguard false
      minifyEnabled false
    }
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
  }
}

repositories {
  flatDir {
    dirs 'libs'
  }
}

dependencies {
  def lifecycle_version = "1.1.0"

  implementation fileTree(dir: 'libs', include: ['*.jar'])
  implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
  implementation 'io.github.tonnyl:spark:0.1.0-alpha'
  implementation 'com.github.Joran-Dob:PlayPauseFab:0.0.3'
  implementation project(':base')
  implementation 'com.android.support:cardview-v7:27.1.1'
  implementation 'com.android.support:recyclerview-v7:27.1.1'
  implementation 'com.github.bumptech.glide:glide:4.4.0'
  implementation "com.squareup.retrofit2:retrofit:2.3.0"
  implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
  implementation "com.squareup.retrofit2:converter-gson:2.3.0"
  implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
  implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
  implementation 'com.spotify.android:auth:1.1.0'
  implementation 'com.spotify.sdk:spotify-player-24-noconnect-2.20b@aar'
  implementation "org.jetbrains.anko:anko:0.10.5"
  implementation 'com.android.support:palette-v7:27.1.1'
  implementation 'com.android.support:appcompat-v7:27.1.1'
  implementation 'com.android.support.constraint:constraint-layout:1.1.0'
  implementation 'com.google.firebase:firebase-core:15.0.2'
  implementation 'com.google.firebase:firebase-database:15.0.1'
  implementation "android.arch.lifecycle:extensions:$lifecycle_version"
  implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // use -ktx for Kotlin
  implementation "android.arch.lifecycle:livedata:$lifecycle_version"
  kapt "android.arch.lifecycle:compiler:$lifecycle_version"
  kapt 'com.github.bumptech.glide:compiler:4.4.0'
  testImplementation 'junit:junit:4.12'
  androidTestImplementation 'com.android.support.test:runner:1.0.2'
  androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
apply plugin: 'com.google.gms.google-services'

com.google.gms.google-services Gradle 插件仅适用于应用 com.android.application 插件的 Android 应用程序模块。它不适用于库模块或功能模块。

当您应用 google-services 插件时,它会使用您的 google-services.json 文件中的信息对您的应用进行更改,使其能够自动初始化。

如果您正在使用功能 (apply plugin: 'com.android.feature' ),那么 apply plugin: 'com.google.gms.google-services' 和 SDK 的 (api 'com.google.firebase.~~~~~~) 需要添加到 baseFeature gradle 文件。

您还应该将 google-services.json 添加到此模块文件夹中!