0

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

My structure looks like this:

  • App
    • Feature
    • Base

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.

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.

Manifest:

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

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'
Joran Dob
  • 330
  • 5
  • 19
  • Possible duplicate of [Make sure to call FirebaseApp.initializeApp(Context) first](https://stackoverflow.com/questions/47887880/make-sure-to-call-firebaseapp-initializeappcontext-first) – Peter Haddad May 12 '18 at 17:20
  • @PeterHaddad I tried adding a class extending activity and adding that to the manifest application name. And calling firebase init in this classes oncreate it gets called but it still crashes with the same error – Joran Dob May 12 '18 at 17:33
  • What were the exact steps that you took to integrate Firebase? Note that the official documentation for that is here: https://firebase.google.com/docs/android/setup – Doug Stevenson May 12 '18 at 17:57
  • @DougStevenson I followed the official docs. My feature gradle file contains implementation 'com.google.firebase:firebase-core:15.0.2' implementation 'com.google.firebase:firebase-database:15.0.1' and apply plugin: 'com.google.gms.google-services' and i added the google-service.json and added classpath 'com.google.gms:google-services:3.3.1' // google-services plugin to the main gradle – Joran Dob May 12 '18 at 18:10

2 Answers2

1

The com.google.gms.google-services Gradle plugin only works with modules that are Android application modules that apply the com.android.application plugin. It doesn't work with library modules or feature modules.

When you apply the google-services plugin, it will make changes to your app that allow it to initialize automatically, using information found in your google-services.json file.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Thanks for this great answer! Added the api 'com.google.firebase:firebase-core:15.0.0' api 'com.google.firebase:firebase-database:15.0.0' and the apply plugin to the build wich has com.android.application but now I'm having trouble importing firebase into the features activities are there any special changes necessary to get a reference to the firebase calls in the feature activities? – Joran Dob May 12 '18 at 18:57
  • If you have a followup question that's different than the original, please ask it separately. – Doug Stevenson May 12 '18 at 18:59
  • Thanks for the feedback! I just did: https://stackoverflow.com/questions/50309893/running-in-to-troubles-with-firebase-integration-into-features – Joran Dob May 12 '18 at 19:19
  • I'm really confused, because the Google analytics sample for instant apps (with features and application gradles) applies the plugin in an feature and also implements the firebase core there, see: https://github.com/googlesamples/android-instant-apps/blob/master/analytics/base/build.gradle – Joran Dob May 14 '18 at 06:58
  • I don't know. Does the sample build the way you expect, if you follow the instructions? It looks like they're only applying the plugin in base, not feature. – Doug Stevenson May 14 '18 at 15:58
  • The sample works as expected and applies com.google.gms.google-services inside the apply plugin: 'com.android.feature' gradle, see:17: https://github.com/googlesamples/android-instant-apps/blob/master/analytics/base/build.gradle – Joran Dob May 14 '18 at 16:56
0

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.

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

Joran Dob
  • 330
  • 5
  • 19