Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use .env variables in Android (java) like we do in laravel?

Tags:

java

android

I don't know if this is off-topic, but in Laravel, we can set variables in a .env file, which we can then access using a getenv() function to prevent from hard coding it in, which can be not secure.

Can we do the same in Android Studio (using Java)? As there is some information I rather not hard code.

Hope this makes sense.

I tried setting the variables in a class and accessing them through the class, but I feel there is a better way that is more similar to how it is done in Laravel.

Here's what I'm doing now but it's not what I'm looking for:

public class EnvVariables {
    public final String API_KEY = "some API key";
    public final String API_ENDPOINT = "https://example.com/api/v1/endpoint";
}

Then I used these variables wherever I needed them.

This does the job, BUT the class is still easily accessible, whereas a .env is not (as it shouldn't be).

like image 731
UndercoverCoder Avatar asked Aug 08 '19 10:08

UndercoverCoder


1 Answers

The closest (In my opinion) we have to environmental variables, would be buildConfig fields, which you make in build.gradle, like this :

buildConfigField "String", "variable_name", "variable_value"

you would do something like this:

 flavorDimensions "default"   
 productFlavors {
    dev {
buildConfigField "String", "SERVER_TEST", "\"http://192.618..\""
buildConfigField "String", "SERVER_MAIN", "\"https://68.5...\""
buildConfigField "String", "API_KEY", "dev API key"
    }
     prod {
buildConfigField "String", "SERVER_TEST", "\"http://192.618..\""
buildConfigField "String", "SERVER_MAIN", "\"https://68.5...\""
buildConfigField "String", "API_KEY", "prod API key"
    }

which you can then access like this :

BuildConfig.API_KEY

have a look at these for more info :

How to generate buildConfigField with String type

and this for creating different flavors :

https://developer.android.com/studio/build/build-variants


As a side note, buildConfig fields are used for values specifically related to a particular build or a group of builds, for your situation of wanting to store API keys it's a good example, but should not be used to just store all constant values for an app.

If you have different versions of an app (free, premium, etc) which uses different API keys, build config is the better way of doing it, as you can see from my code above, depending on the build variant you launch, the api key will change.

like image 83
a_local_nobody Avatar answered Oct 20 '22 00:10

a_local_nobody