raklos
raklos

Reputation: 28545

Storing configs in android

I'm trying to work out where the best place to put config type data is. At the moment everything is hardcoded in java e.g API endpoint URLs, API keys etc. Can they just go in strings resources? or in a static class?

side note - is it safe to keep API keys like this?

Upvotes: 1

Views: 835

Answers (2)

comrade
comrade

Reputation: 4710

There are some options to use:

1.Static class (something like Config.java) or singleton object. For example:

public enum Config {
    INSTANCE;

    public static final String CLOUD_ID = "8888888888";
}

2.String resources (strings.xml or separate string file like api.xml). For example:

 <string name="google_cloud_message_register_id" translatable="false">8888888888</string>

3.Integer resources (xml file like integers.xml). For example:

<resources>
    <integer name="category_id">777</integer>
</resources>

4.SharedPreferences storage. For example:

mSharedPreferences.edit().putString(AUTH_EMAIL_KEY, authEmail).commit(); // to save
mSharedPreferences.getString(AUTH_EMAIL_KEY, null); // to get

5.External storage (i.e. files)

6.SQLite database

7.Gradle build script configuration. For example:

// in build.gradle
buildTypes {
    release {
        buildConfigField "String", "API", "\"https://api.com/api/\""
    }
}

BuildConfig.API // access in Java code

For API endpoint URLs, public API keys etc. I prefer to use Gradle build script configuration. It's very flexible and different values can be used with various build types.

Encrypted SQLite table can be used to store delicate private data but the best way to save private data is load them from protected external server, I think.

Upvotes: 2

earthw0rmjim
earthw0rmjim

Reputation: 19417

SharedPreferences might be your best bet to store configurations for your app.

It is basically designed for this kind of data storage. Although it is accessible by other apps with superuser privileges on a rooted device, so you might want to encrypt sensitive data.

On an unrooted device it can only be accessed by the app, it is safe on code level.

Check out the developer's guide.

If your configuration never changes, a static class could also be an option.

Upvotes: 3

Related Questions