在用Kotlin编写的Modulair Android项目中初始化Firebase会产生未初始化的错误 [英] Initializing Firebase in Modulair Android project written in kotlin gives not initialized error

查看:84
本文介绍了在用Kotlin编写的Modulair Android项目中初始化Firebase会产生未初始化的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试将Firebase实施到以kotlin编写的modulair android项目中时遇到困难.

I'm having difficulty trying to implement firebase into an modulair android project written in kotlin.

我的结构如下:

  • 应用
    • 功能
    • 基础
    • App
      • Feature
      • Base

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

      And then in my main activity oncreate I'm calling the 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 }
      }
      

      我的带有实时数据的视图模型如下:

      My viewmodel with livedata looks like this:

          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
      
        }
      }
      

      但是当我尝试运行该应用程序时,我会收到此消息

      But when i try to run the app i'm getting this message

        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.
      

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

      I also tried creating an class extending my application and calling firebaseapp.initialize(this) and adding this to my manifest but i still got the same error.

      清单:

       <?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:

      BaseApplication.kt:

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

      我的功能gradle

      My feature 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'
      

      推荐答案

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

      If you are using features (apply plugin: 'com.android.feature' ) then the apply plugin: 'com.google.gms.google-services' and the SDK's (api 'com.google.firebase.~~~~~~) need to be added to the baseFeature gradle file.

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

      You should also add the google-services.json to this modules folder!

      这篇关于在用Kotlin编写的Modulair Android项目中初始化Firebase会产生未初始化的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆