BuildTypes.each String for API in Android Gradle configuration

I am working on a Google Udacity course for the new Android Devs, and I ran into some problems with the Gradle construct and defining a constant in it. I tried to surround the field with several options "," and "\", which, as I said, is recommended on the Internet, but nothing works. I was wondering how to format the string inside buildTypes.each seen here?

buildTypes.each { it.buildConfigField "String", "OPEN_WEATHER_MAP_API_KEY", **APICodeHere** } 

Here is all the code for the Gradle build application.

 android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { applicationId "com.example.android.sunshine.app" minSdkVersion 10 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } buildTypes.each { it.buildConfigField "String", "OPEN_WEATHER_MAP_API_KEY", **APICodeHere** } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.2' } 

Thanks!!!

+5
source share
3 answers

I am also doing this course, and I had the same problem. The formatting that eventually worked for me is the following:

 it.buildConfigField 'String', 'OPEN_WEATHER_MAP_API_KEY', "\"6df0...9ac\"" 

Insert your open weather hexadecimal API key instead of 6df0...9ac above. Hope this helps!

+9
source

you can make it visible through github by calling it from the folder that you open as part of the project package.

 app.gradle: def keystorePropertiesFile = rootProject.file("keystore.properties") def keystoreProperties = new Properties() keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) buildTypes.each { it.buildConfigField 'String', 'youtubeapi', keystoreProperties['YoutubeApi'] }` project.keystore.properties: YoutubeApi="keykeykeykeykapikey"; 
0
source

Gradle creates a BuildConfig file to store the variables it creates, such as VERSION_CODE , APPLICATION_ID, and others.

So what you need to do is put the buildTypes.each{} statement inside your app.gradle file to create some new variables that you want to create there.

In your app.gradle file, your code should look something like this:

  ... buildTypes{ release { bla bla bla } buildTypes.each { it.buildConfigField("TYPE_OF_PARAM", "PARAM_NAME", "PARAM_VALUE") } } 

Where

  • TYPE_OF_PARAM is the type you want to set for your "variable" (for example, String).
  • PARAM_NAME is the name of your newly created variable.
  • PARAM_VALUE is the value you want to set for your variable.

IMPORTANT

If you set a new String variable, you must use \" to set the quotation marks in your new variable. So, if I set the String, I have to change PARAM_VALUE to "\"My String\"" . So when gradle sets your variable String, it will also set quotation marks.

Hope this helps someone.

0
source

All Articles