androidandroid-studiogradlebuild.gradleandroid-build

Unresolved reference for BuildConfig field in Android Studio when using buildConfigField


I’m trying to pass a local environment variable into my Android project via Gradle and then access it in my Kotlin code. The idea is to configure Firebase Emulator host dynamically.

In my app/build.gradle I defined the following:

android {
...

buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        buildConfigField "String", "FIREBASE_EMULATOR_HOST", "\"\""
    }
    debug {
        def firebaseHost = System.getenv("FIRE_BASE_EMULATOR_IP") ?: "10.0.2.2"
        buildConfigField "String", "FIREBASE_EMULATOR_HOST", "\"${firebaseHost}\""
    }
}

In my Kotlin code I want to use this fild like:

dataBase.useEmulator(BuildConfig.FIREBASE_EMULATOR_HOST, 9001)

However, Android Studio shows the error: Unresolved reference: FIREBASE_EMULATOR_HOST

My setup: Android Studio: Android Studio Narwhal 3 Feature Drop | 2025.1.3

Gradle: 8.9

sourceCompatibility JavaVersion.VERSION_19

jvmTarget = JavaVersion.VERSION_19.toString()

kotlinCompilerExtensionVersion '1.5.14'

What I tried

Why is the BuildConfig.FIREBASE_EMULATOR_HOST field not recognized in my code? How can I correctly pass environment variables to Gradle and then access them in my Kotlin code using BuildConfig?


Solution

  • You need to set buildConfig = true in order to add/generate buildConfigField in your app gradle file...

    android {
        ##namespace 'xxx.xxx.xxx.xxx'
        ##compileSdk 36
        buildFeatures {
           buildConfig true
        }
        
    }
    

    Happy coding ....