Gradle buildConfigField BuildConfig cannot resolve

2019-01-31 11:07发布

I am using Gradle to build my Android application. I am trying to use some flags based on the build type (release or debug).

My Gradle file looks like this:

android {
    buildTypes {
        debug {
            buildConfigField 'boolean', 'PREPROD', 'true'
            buildConfigField 'boolean', 'STAGING', 'false'
        }

        release {
            buildConfigField 'boolean', 'PREPROD', 'false'
            buildConfigField 'boolean', 'STAGING', 'false'
        }
    }
}

And if I try to call BuildConfig.PREPROD or BuildConfig.STAGING I get a "Cannot resolve symbol" error. The Gradle sync was successful, so I don't know if I forgot some steps in order to be able to use this feature?

The generated BuildConfig.java file is the following (in build/source/buildConfig/debug/com.example.myapp):

package com.example.myapp;

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

9条回答
聊天终结者
2楼-- · 2019-01-31 11:41

Happened to me because I did not declared a String field properly.

I forgot the escaping characters. Changing from :

buildConfigField "String", "FOO", "foo"

to

buildConfigField "String", "FOO", "\"foo\""

solved the problem.

查看更多
来,给爷笑一个
3楼-- · 2019-01-31 11:49

Search for occurrences of BuildConfig. I had a rogue import of non-existant BuildConfig and the compiler instead of catching that pointed at a random line of code somewhere else!

查看更多
够拽才男人
4楼-- · 2019-01-31 11:50

Make sure you add your parameter also to the defaultConfig. You are probably running the default buildVarient while your parameter is defined in a speciffic buildVariant.

in the build gradle file use this:

 defaultConfig {
        buildConfigField('String' , 'myParameter', 'someValue')
    }

Then, in the code use this:

String myParam= BuildConfig.myParameter;

Hope this helps, M.A :)

查看更多
登录 后发表回答