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

Firebase初始化异常求助:Default FirebaseApp未初始化问题排查

Firebase初始化报错求助:Default FirebaseApp is not initialized

编译时出现如下错误:

Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process [appname] Make sure to call FirebaseApp.initializeApp(Context) first.

已尝试调整com.google.firebase:firebase-auth和com.google.gms:google-services的依赖版本,但问题未解决。以下是项目关键代码文件,求帮忙排查:


项目级build.gradle

ext {
        nav_version = "2.5.3"
    }

    repositories {
        google()
        mavenCentral()
        gradlePluginPortal()
    }

    dependencies {
            classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
            classpath 'com.android.tools.build:gradle:7.3.1'
            classpath 'com.google.gms:google-services:4.3.7'
            classpath 'com.google.firebase:firebase-plugins:2.0.0'
    }
    }

    plugins {
        id 'com.android.application' version '7.3.1' apply false
        id 'com.android.library' version '7.3.1' apply false
        id 'org.jetbrains.kotlin.android' version '1.7.20' apply false
        id("com.google.gms.google-services") version "4.4.0" apply false
    }

模块级build.gradle

id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'com.google.gms.google-services' // Firebase
    id 'kotlin-kapt'//Navigation
}

android {
    namespace 'com.example.dine_aid'
    compileSdk 34

    packagingOptions {
        exclude 'META-INF/AL2.0'
        exclude 'META-INF/LGPL2.1'
    }

    defaultConfig {
        applicationId "com.example.dine_aid"
        minSdk 28
        targetSdk 34
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            def keystorePropertiesFile = rootProject.file("keystore.properties")
            def keystoreProperties = new Properties()
            keystoreProperties.load(new FileInputStream(keystorePropertiesFile))

            buildConfigField "String", "API_TOKEN", keystoreProperties["API_TOKEN"]
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        dataBinding true
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.12.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.10.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'com.android.car.ui:car-ui-lib:2.5.1'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
    // Firebase
    implementation 'com.google.firebase:firebase-auth:21.0.1'
    implementation 'com.google.firebase:firebase-core:21.1.1'
    //RecyclerView
    implementation("androidx.recyclerview:recyclerview:1.3.1")
    //ImageLoader Coil
    implementation("io.coil-kt:coil:2.2.2")
    //Retrofit
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-moshi:2.9.0"
    implementation "com.squareup.moshi:moshi-kotlin:1.14.0"
    //Material
    implementation 'com.google.android.material:material:<version>'
    //Navigation
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    //Glide
    implementation 'com.github.bumptech.glide:glide:4.14.2'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
    // Coil
    implementation "io.coil-kt:coil:2.2.2"
    // HTML parsing Jsoup
    implementation 'org.jsoup:jsoup:1.14.3'
    //Nested ScrollView
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'

    implementation 'com.google.gms:google-services:4.0.0'

}

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'  // Google Services plugin

FirebaseViewModel.kt

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.firebase.FirebaseApp
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser

class FirebaseViewModel(application: Application) : AndroidViewModel(application) {

    private val firebaseAuth: FirebaseAuth = FirebaseAuth.getInstance()

    private val _currentUser = MutableLiveData<FirebaseUser?>(firebaseAuth.currentUser)
    val currentUser : LiveData<FirebaseUser?>
        get() = _currentUser

}

Login_Fragment.kt

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.findNavController
import com.example.dine_aid.R
import com.example.dine_aid.databinding.LoginScreenBinding
import com.example.dine_aid.model.FirebaseViewModel
import com.example.dine_aid.model.MainViewModel
import com.google.firebase.FirebaseApp

class Login_Fragment : AppCompatActivity() {

    private lateinit var binding: LoginScreenBinding

    private lateinit var firebaseViewModel: FirebaseViewModel

    private lateinit var viewModel: MainViewModel

    private lateinit var userMail : String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        FirebaseApp.initializeApp(this)

        binding = LoginScreenBinding.inflate(layoutInflater)
        setContentView(binding.root)

        firebaseViewModel = ViewModelProvider(this)
            .get(
                FirebaseViewModel::class.java
            )

        firebaseViewModel.currentUser.observe(this) {
            if (it == null) {
                findNavController(
                    androidx.navigation.fragment.
                    R.id.nav_host_fragment_container
                ).navigate(
                        R.id.login_Fragment
                    )
            }
        }
    }
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:enableOnBackInvokedCallback="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Dine_aid"
        tools:targetApi="34">

        <activity
            android:name="com.example.dine_aid.FullScreenImageActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>


        <activity
            android:name=".UI.login.Login_Fragment"
            android:windowSoftInputMode="stateHidden"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>

        <meta-data
            android:name="preloaded_fonts"
            android:resource="@array/preloaded_fonts" />
    </application>

</manifest>

排查关键点

  1. 清理重复的Google Services插件配置

    • 项目级build.gradle中,删除buildscript.dependencies里的classpath 'com.google.gms:google-services:4.3.7',保留plugins块的id("com.google.gms.google-services") version "4.4.0" apply false即可。
    • 模块级build.gradle中,删除底部重复的apply plugin: 'com.google.gms.google-services',同时删除dependencies里的implementation 'com.google.gms:google-services:4.0.0'(这是插件而非依赖库,无需添加)。
  2. 提前Firebase初始化时机

    • 创建自定义Application类,在onCreate中初始化Firebase,确保在ViewModel创建前完成初始化:
      class MyApplication : Application() {
          override fun onCreate() {
              super.onCreate()
              FirebaseApp.initializeApp(this)
          }
      }
      
    • 在Manifest的application标签中添加android:name=".MyApplication"。
  3. 修复依赖问题

    • 删除implementation 'com.google.firebase:firebase-core:21.1.1',新版Firebase已废弃该依赖。
    • 删除模块级build.gradle中无效的implementation 'com.google.android.material:material:<version>'(已有同依赖的1.10.0版本)。
    • 升级Firebase Auth到与google-services插件匹配的最新稳定版,避免版本不兼容。

内容的提问来源于stack exchange,提问作者a-bytecode

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 10:12:05