Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle buildConfigField: Syntax for arrays & maps?

Tags:

The android gradle documentation says about buildConfigField:

void buildConfigField(String type, String name, String value) 

Adds a new field to the generated BuildConfig class. The field is generated as: type name = value;

This means each of these must have valid Java content. If the type is a String, then the value should include quotes.

I can't find any information about the syntax of buildConfigField values for Arrays, Arraylist or a HashMap? Since they are compiled into java code usually everything should be possible.

Does anyone has some examples or documentation?

like image 238
Fahim Avatar asked Feb 09 '17 07:02

Fahim


2 Answers

For array

app.gradle

        buildConfigField "String[]", "URL_ARRAY",         "{" +         "\"http:someurl\"," +         "\"http:someurl\"," +         "\"http:someurl\"" +         "}" 

For Map

        buildConfigField "java.util.Map<String, String>", "NAME_MAP",                   "new java.util.HashMap<String, " +                  "String>() {{ put(\"name\", \"John\"); put(\"name1\",  \"John\"); put(\"name2\", " +                 "\"John\"); }}" 

Access in code:

HashMap<String, String> name = (HashMap<String, String>) BuildConfig.NAME_MAP; 
like image 141
Anurag Singh Avatar answered Oct 06 '22 13:10

Anurag Singh


IMHO the reason for using buildConfig fields is to keep important data out of the code - like environment variables.

another example - static arrays + gradle.properties (requires Gradle 2.13 or above):

gradle.properties:

 nonNullStringArray=new String[]{ \n\     \"foo\",\n\     \"bar\"\n}  

build.gradle:

buildConfigField "String[]", "nonNullStringArray", (project.findProperty("nonNullStringArray") ?: "new String[]{}")  buildConfigField "String[]", "nullableStringArray", (project.findProperty("nullableStringArray") ?: "null")   
like image 41
Lukas Avatar answered Oct 06 '22 13:10

Lukas