BuildConfig not getting created correctly (Gradle Android)

AndroidGradleAndroid BuildAndroid Gradle-PluginBuildconfig

Android Problem Overview


I am trying to convert our Android application to a gradle build. I have the project and it's libraries building successfully. I am now trying to create separate apks for our various environments (dev/test/prod have different urls for the restful services they consume).

In searching around, the best way that I feel to do this is with making different BuildConfig for each environment. This is what I tried:

import java.util.regex.Pattern

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:+'
    }
}

apply plugin: 'android'

task('increaseVersionCode') << {
    def manifestFile = file("AndroidManifest.xml")
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig') {
        task.dependsOn 'increaseVersionCode'
    }
}

dependencies {
	compile 'com.android.support:support-v4:19.0.0' 
    compile files('libs/commons-io-2.4.jar',
    	          'libs/google-play-services.jar',
    	          'libs/gson-2.2.4.jar',
    	          'libs/universal-image-loader-1.8.6.jar',
    	          'libs/wakeful-1.0.1.jar')
	compile project(':pulltorefresh_lib')
	compile project(':edgeeffect_lib')
	compile project(':viewpagerindicator_lib')        
}

android {
	buildToolsVersion "18.1.1"
    compileSdkVersion "Google Inc.:Google APIs:18"
    
	defaultConfig { 
       minSdkVersion 14
       targetSdkVersion 18
	}

	buildTypes {
		debug {
			packageNameSuffix ".debug"
		}
		dev.initWith(buildTypes.debug)
		dev {
			buildConfigField "String", "URL_SEARCH", "\"https://dev-search.example.com\";"
			buildConfigField "String", "URL_CONNECT", "\"https://dev-connect.example.com\";"
			buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://dev-mobilenews.example.com/newslist\";"
			buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://dev-mobilenews.example.com/newsdetail\";"
			buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://dev-mobilenews.example.com/registerendpoints\";"
		}
		prod.initWith(buildTypes.release)
		prod {
			buildConfigField "String", "URL_SEARCH", "\"https://search.example.com\";"
			buildConfigField "String", "URL_CONNECT", "\"https://connect.example.com\";"
			buildConfigField "String", "URL_SVC_NEWSLIST", "\"https://mobilenews.example.com/newslist\";"
			buildConfigField "String", "URL_SVC_NEWSDETAIL", "\"https://mobilenews.example.com/newsdetail\";"
			buildConfigField "String", "URL_SVC_REGISTERENDPOINTS", "\"https://mobilenews.pdc-np-cf.lmig.com/registerendpoints\";"			
		}
	}
  
	sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

The problem is that my BuildConfig.java doesn't seem to get the static variables injected, therefore I get errors similar to:

/Users/path/to/project/MainActivity.java:348: error: cannot find symbol
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_SEARCH)));
			                                                                  ^
  symbol:   variable URL_SEARCH
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:359: error: cannot find symbol
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(BuildConfig.URL_CONNECT)));
			                                                                  ^
  symbol:   variable URL_CONNECT
  location: class BuildConfig
/Users/path/to/project/MainActivity.java:600: error: cannot find symbol
			HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_REGISTERENDPOINTS);
			                                            ^
  symbol:   variable URL_SVC_REGISTERENDPOINTS
  location: class BuildConfig
/Users/path/to/project/service/AlarmNotificationService.java:145: error: cannot find symbol
		String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
		                               ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:240: error: cannot find symbol
		String requestUrl = BuildConfig.URL_SVC_NEWSLIST + "?"
		                               ^
  symbol:   variable URL_SVC_NEWSLIST
  location: class BuildConfig
/Users/path/to/project/service/NewsService.java:530: error: cannot find symbol
			HttpPost httpPost = new HttpPost(BuildConfig.URL_SVC_NEWSDETAIL);
			                                            ^
  symbol:   variable URL_SVC_NEWSDETAIL
  location: class BuildConfig
6 errors

My build/source/buildConfig/debug/com/.../BuildConfig.java file contains:

/**
 * Automatically generated file. DO NOT MODIFY
 */
package com....;

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String PACKAGE_NAME = "com.....debug";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 5;
}

What am I doing wrong?

Android Solutions


Solution 1 - Android

Please, be sure that you are building "dev" or "prod" variant. There is no BuildConfig definition in default "debug" and "release" variant. In Android Studio, you can select current variant in bottom left corner:

Build Variants

To simplify your build.gradle file, you can define:

buildTypes {
    debug {
        buildConfigField "String", "URL_SEARCH", "\"https://dev-search.example.com\""
        // etc.
    }
    release {
        buildConfigField "String", "URL_SEARCH", "\"https://search.example.com\""
        // etc.      
    }
}

and then just use default "debug" and "release" variants.

At last, delete semicolon (sign: ';') from the value of buildConfigField parameter.

Solution 2 - Android

I had same issue and fixed it like below:

buildConfigField 'String', 'BASE_URL', '"https://api.example.com"'

Solution 3 - Android

first do

File -> Invalidate Caches/Restart... -> Invalidate and Restart 

then do

Build -> Clean Project

then do

Build - > Rebuild Project 

Solution 4 - Android

Just in case that helps somebody else, in my case it was a missing import: import uk.co.yourpackage.yourapp.BuildConfig;

Somehow, nowhere in the doc does it mention you need that include! Made me think it was automatically imported somehow but it ISN'T. not for me at least... So much time lost... Hope that helps another newbie like me!

Solution 5 - Android

Try to do

> Build -> Clean Project

then do

> Build - > Rebuild Project

If it doesn't work, try

> File -> Invalidate Caches/Restart... -> Invalidate and Restart

then do

> Build -> Clean Project

then do

> Build - > Rebuild Project

Solution 6 - Android

Here is what fixed this for me:

File -> Invalidate Caches/Restart... -> Invalidate and Restart 

Solution 7 - Android

If you are modifying your Environment Variables, and they are not reflecting correctly in Android studio try doing:

Build -> Clean Project 
File -> Invalidate Caches/Restart... -> Invalidate and Restart 

Solution 8 - Android

I solve this problem as given below in this case Android studio will generate Build Config file itself

File -> Sync Project with Gradle Files

Solution 9 - Android

In the project.ext.envConfigFiles array, ensure you set the debug to the right .env file you are using for development

Solution 10 - Android

I did all the things in the answers but still didn't work. I solved my problem by changing the package name in the manifest.xml file which still hadn't been updated :

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

Solution 11 - Android

After trying everything, switching the build variant and selecting Build > Make Project worked for me.

Solution 12 - Android

I had similar problem related to build types being setup using .initWith(someotherbuildtype), BuildConfig was not being created properly. I had to switch to the parent build variant and build that first, then the build types that initWith the parent built fine.

Solution 13 - Android

In my case, I was expecting the BuildConfig for my new gradle module created. But forgot to add it as a dependency in app: module.

Solution 14 - Android

In my case there was an string field resValue "string", "app_name", "MyApp" in strings.xml as well as in product flavours.

I did Invalidate Caches then Rebuild then android studion given the actual error of duplicate resources.

so Invalidate caches -> Rebuild -> Remove string resources which were already in buildconfigfield resvalue worked for me

I was using Android Studio Bumblebee 2021.1.1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInnovaView Question on Stackoverflow
Solution 1 - AndroidPeter KnutView Answer on Stackoverflow
Solution 2 - AndroidsavepopulationView Answer on Stackoverflow
Solution 3 - AndroidMirza Ahmed BaigView Answer on Stackoverflow
Solution 4 - AndroidLitomeView Answer on Stackoverflow
Solution 5 - AndroidRifatView Answer on Stackoverflow
Solution 6 - AndroidbartonstanleyView Answer on Stackoverflow
Solution 7 - AndroidJmzView Answer on Stackoverflow
Solution 8 - AndroidibrokhimView Answer on Stackoverflow
Solution 9 - Androidchisom onwuegbuzieView Answer on Stackoverflow
Solution 10 - Androidnarcis dprView Answer on Stackoverflow
Solution 11 - AndroidraviView Answer on Stackoverflow
Solution 12 - AndroidstrayaView Answer on Stackoverflow
Solution 13 - AndroidcgrView Answer on Stackoverflow
Solution 14 - AndroidGopal Singh SirviView Answer on Stackoverflow