BuildConfig not getting created correctly (Gradle Android)
Asked Answered
I

22

121

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?

Inseverable answered 20/12, 2013 at 15:2 Comment(3)
Might make sense to remove those Liberty references. Not that there's any critical code here, but it's best to avoid sharing proprietary code on StackOverflow ;)Keek
see below link: #22605127Accrual
Check answer here #22605127Lupus
B
87

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.

Belorussia answered 20/12, 2013 at 16:6 Comment(3)
Thanks...it was me being daft, as I expected. "gradle installDev" works fine...."gradle build" was giving me errors.Inseverable
you can also go like this buildConfigField 'String', 'URL_SEARCH', '"https://search.example.com"'Iinde
I want to add that you might require to rebuild the project (Build -> Rebuild Project) when changing the active build variant else the BuildConfig will not be regenerated.Ephesian
O
150

In my case I had to enable buildConfig as a build feature.

android {
    buildFeatures {
        buildConfig true
    }
}
Occupant answered 14/2, 2023 at 15:33 Comment(10)
and after that do this : File -> Sync Project with Gradle FilesAlchemy
You need to clean the project and rebuild it after doing thisIceman
It worked for me. But why do we need to add buildConfig true. I did not get this.Berdichev
The only one solution works for me (saved my day)Newmown
This happened to be a solution for me on Android Studio Giraffe. Thank youBlondie
The only right answer, tksShortening
Right answer for me, thanks!Heartache
Okey, this is for me working.Clausewitz
Thank you. 9 years after your answer, you are more more right than ever, because AGP 8.0 changed the default value of buildConfig from true to false. developer.android.com/build/releases/past-releases/…Atombomb
I want to also mention that you need to put this in each of your modules' build.gradle files if you have more than one, because the gradle.properties entry was applying to all modules but this won't.Milan
B
87

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.

Belorussia answered 20/12, 2013 at 16:6 Comment(3)
Thanks...it was me being daft, as I expected. "gradle installDev" works fine...."gradle build" was giving me errors.Inseverable
you can also go like this buildConfigField 'String', 'URL_SEARCH', '"https://search.example.com"'Iinde
I want to add that you might require to rebuild the project (Build -> Rebuild Project) when changing the active build variant else the BuildConfig will not be regenerated.Ephesian
P
63

first do

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

then do

Build -> Clean Project

then do

Build - > Rebuild Project 
Prague answered 9/4, 2020 at 6:8 Comment(3)
After doing this Gradle finally reported that the minimum SDK of one of the libraries used is higher than the apps minsdkMaffick
confirm, it workedSweatshop
Hurray ! It works! Thank you @Mirza AhmedWald
C
58

I had same issue and fixed it like below:

buildConfigField 'String', 'BASE_URL', '"https://api.example.com"'
Cecilia answered 22/10, 2015 at 13:40 Comment(2)
for String, double-quotation does NOT generate properly. only single-quotation generates variable successfully.Vinia
For those like me who missed it the first time, the key part is that the value is in double-quotes inside of the single-quotes.Krak
S
23

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!

Septimal answered 27/7, 2015 at 20:20 Comment(3)
Amazing , it was import problem, I was import from android.support.v4.BuildConfig Thank you :)Cienfuegos
I had "org.koin.android" imported by accident and it has its own BuildConfig for some reason. Thank you for this comment, it reminded me to manually check the import!Carlile
I have tried virtually everything to no luckMirandamire
K
19

Add this in app build.gradle

buildFeatures {
    buildConfig = true
}

if using jet pack compose

 buildFeatures {
        compose = true
        buildConfig = true
    }
Kathe answered 20/9, 2023 at 10:50 Comment(0)
C
13

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

Caespitose answered 18/4, 2020 at 5:37 Comment(1)
Clean and rebuild should work - worked for me.Kozak
N
13

You need to have this line in your gradle.properties file:

android.defaults.buildfeatures.buildconfig=true

Hope this helps

Nickname answered 1/8, 2023 at 13:46 Comment(0)
E
7

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

File -> Sync Project with Gradle Files
Earwitness answered 23/12, 2020 at 3:42 Comment(2)
This one helped meRusk
work for me . thanks!! (android studio 2020.03.01 patch.3 )Albumen
D
6

Very logical Answer if this is not heppening in compose

    buildFeatures {
    // The first line should already be in your project!
    compose = true
    buildConfig = true
    }

This will now generate the file and you can use the BuildConfig.Debug in Application and everywhere.

Dinsmore answered 27/6, 2023 at 10:10 Comment(0)
A
5

For Android Studio Version

Android Studio Dolphin | 2021.3.1 Patch 1

Build #AI-213.7172.25.2113.9123335, built on September 30, 2022

Runtime version: 11.0.13+0-b1751.21-8125866 aarch64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.

What was I trying to do?

I set up three build variants for the app module, I wanted BuildConfig to be changed every time I change the build variant, for that particular variable defined in the build.gradle (app) configurations.

What didn't work

I have tried all three methods, DIDN'T WORK AT ALL, to regenerate my BuildConfig for the build variant I was changing:

  1. File > invalidate cache and restart along with Build > Clean Project & Build > Rebuild Project
  2. Build > Make Project alone
  3. File > Sync Project with Gradle Files alone

What worked

Then I tried a combination which is surprisingly WORKING WELL:

  1. First, Try Build > Make Project
  2. Then File > Sync Project with Gradle Files

I hope it will work for that particular version I am not sure for other versions of Android Studio.

Thanks, @ravi, and @ibrokhim for partially answered for the case.

Amphetamine answered 25/11, 2022 at 10:6 Comment(2)
This one worked for Android Studio Flamingo | 2022.2.1 Patch 2 too on Macbook air M2. Confirmed!Egest
@Egest Happy to know the solution is still working for the latest updates of Android Studio, cheers man. And I would suggest you to edit the answer in a appropriate manner so that it may helpful for others as well.Amphetamine
I
4

Here is what fixed this for me:

File -> Invalidate Caches/Restart... -> Invalidate and Restart 
Illustrious answered 20/2, 2019 at 21:19 Comment(0)
A
4

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 
Audible answered 13/3, 2020 at 20:15 Comment(0)
S
3

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">
Saudra answered 24/10, 2020 at 5:53 Comment(0)
H
3

Follow these steps:

Step 1

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

Step 2

Build -> Clean Project

Step 3

Build - > Rebuild Project 
Huh answered 5/7, 2022 at 4:28 Comment(0)
K
2

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

Karyn answered 27/10, 2021 at 11:23 Comment(0)
S
1

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

Stephenson answered 9/7, 2019 at 8:12 Comment(0)
D
0

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.

Depreciate answered 27/4, 2015 at 0:56 Comment(0)
H
0

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.

Honorary answered 29/7, 2021 at 12:1 Comment(0)
P
0

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

Pathy answered 8/2, 2022 at 13:0 Comment(0)
S
0

None of the solutions worked for me, I closed the project and opened again, and then rebuilt it because it clears all the generated stuff on closing and it worked, thank you.

Souterrain answered 15/12, 2022 at 7:6 Comment(0)
G
0

In My Case I have First

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

When project Restarts than

Build -> Clean Project

After Cleaning`

    Build -> Rebuild Project
Gainor answered 26/1 at 6:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.