48

What is the best way and how do I set up a configuration file for a application?

I want the application to be able to look into a text file on the SD card and pick out certain information that it requires.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Beginner
  • 28,539
  • 63
  • 155
  • 235
  • 3
    What is this config file for? Do you need to save user settings or similar? There's a lot of good guides with using SharedPreferences and similar. – Codemonkey Feb 28 '11 at 10:07
  • It is for now to load a name for the pda into the application, and then i want the ability to change this name in future without having to change code in the application – Beginner Feb 28 '11 at 12:37
  • Be sure to check the linked question. The .properties answer there is what I wanted out of this question. It also looks like what @Beginner was looking for. – Hovis Biddle Feb 15 '12 at 23:39
  • Do you mean `/default.prop`? – neverMind9 Jul 23 '19 at 21:21

4 Answers4

119

If your application is going to be released to the public, and if you have sensitive data in your config, such as API keys or passwords, I would suggest to use secure-preferences instead of SharedPreferences since, ultimately, SharedPreferences are stored in an XML in clear text, and on a rooted phone, it is very easy for an application to access another's shared preferences.

By default it's not bullet proof security (in fact it's more like obfuscation of the preferences) but it's a quick win for incrementally making your android app more secure. For instance it'll stop users on rooted devices easily modifying your app's shared prefs. (link)

I would suggest a few other methods:

*Method 1: Use a .properties file with Properties

Pros:

  1. Easy to edit from whatever IDE you are using
  2. More secure: since it is compiled with your app
  3. Can easily be overridden if you use Build variants/Flavors
  4. You can also write in the config

Cons:

  1. You need a context
  2. You can also write in the config (yes, it can also be a con)
  3. (anything else?)

First, create a config file: res/raw/config.properties and add some values:

api_url=http://url.to.api/v1/
api_key=123456

You can then easily access the values with something like this:

package some.package.name.app;

import android.content.Context;
import android.content.res.Resources;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public final class Helper {
    private static final String TAG = "Helper";

    public static String getConfigValue(Context context, String name) {
        Resources resources = context.getResources();

        try {
            InputStream rawResource = resources.openRawResource(R.raw.config);
            Properties properties = new Properties();
            properties.load(rawResource);
            return properties.getProperty(name);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Unable to find the config file: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "Failed to open config file.");
        }

        return null;
    }
}

Usage:

String apiUrl = Helper.getConfigValue(this, "api_url");
String apiKey = Helper.getConfigValue(this, "api_key");

Of course, this could be optimized to read the config file once and get all values.

Method 2: Use AndroidManifest.xml meta-data element:

Personally, I've never used this method because it doesn't seem very flexible.

In your AndroidManifest.xml, add something like:

...
<application ...>
    ...

    <meta-data android:name="api_url" android:value="http://url.to.api/v1/"/>
    <meta-data android:name="api_key" android:value="123456"/>
</application>

Now a function to retrieve the values:

public static String getMetaData(Context context, String name) {
    try {
        ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        Bundle bundle = ai.metaData;
        return bundle.getString(name);
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(TAG, "Unable to load meta-data: " + e.getMessage());
    }
    return null;
}

Usage:

String apiUrl = Helper.getMetaData(this, "api_url");
String apiKey = Helper.getMetaData(this, "api_key");

Method 3: Use buildConfigField in your Flavor:

I didn't find this in the official Android documentation/training, but this blog article is very useful.

Basically setting up a project Flavor (for example prod) and then in your app's build.gradle have something like:

productFlavors {
    prod {
        buildConfigField 'String', 'API_URL', '"http://url.to.api/v1/"'
        buildConfigField 'String', 'API_KEY', '"123456"'
    }
}

Usage:

String apiUrl = BuildConfig.API_URL;
String apiKey = BuildConfig.API_KEY;
Pang
  • 9,564
  • 146
  • 81
  • 122
grim
  • 6,669
  • 11
  • 38
  • 57
  • Great answer with all necessary details. Flavor will be the apt option in most cases. Thanks for spending time to post this answer – sunil Apr 14 '16 at 12:51
  • so i'm eyeing solutions 1 and 3, but my use case (which i'm sure is a common one) is to have a dynamic API host address but with resource paths that are shared by all build variants. essentially what i'm looking for is a text file to store the key/value pairs (in whatever format) in the default/global space (ie. main) and then a build variant specific one, then squishing those objects together with the build variant taking precedence. does this exist? i've read about `SharedPreferences` but this seems for user input at runtime, and i've read about people using a class to hold... – Justin Jun 09 '16 at 22:42
  • constants, but that doesn't quite fit either as i don't get any benefit of a specific configuration values overriding common ones. – Justin Jun 09 '16 at 22:44
  • @Justin I've never worked with dynamic API host address; in my case, the servers' IP would change (load balancing), not the API's endpoint. If I'm understanding your question correctly, you can use `SharedPreferences`, `secure-preferences`, a database (SQLite, Realm, ...) , or create/save a file (*.properties or other) on the device to store key/value pairs - although I think that saving a file requires permissions. Ultimately you'd also have to implement the precedence between the key/value sources. In any case, I think you should post a question as this is out of scope for this one. – grim Jun 12 '16 at 23:20
  • Very nice answer and great explanation. Thanks. – Sachin Tanpure Mar 06 '18 at 10:04
10

You can achieve this using shared preferences

There is a very detailed guide on how to use Shared Preferences on the Google Android page https://developer.android.com/guide/topics/data/data-storage.html#pref

Reno
  • 33,594
  • 11
  • 89
  • 102
  • 3
    O right i thought of shared preferences like global variables not config file, you can see i come from a web development background not mobile :) – Beginner Feb 28 '11 at 10:32
  • 2
    Any example of a shared preference text file, and an activity accessing this ? – Beginner Feb 28 '11 at 10:33
  • 6
    how can shared preferences be used as config sources? I see config as some "hardcoded" file (json, xml etc) with developer set data to be used inside the application. Shared preferences may hold data you generate within your application, but how do they come with pre-set data inside them? – Carlo Moretti Jan 24 '18 at 15:59
  • 11
    shared preference CANNOT act like configuration file. – us_david Aug 23 '18 at 17:38
8

If you want to store the preferences of your application, Android provides SharedPreferences for this.
Here is the link to official training resource.

Mudassir
  • 13,031
  • 8
  • 59
  • 87
  • Any example of a shared preference text file, and an activity accessing this ? – Beginner Feb 28 '11 at 10:33
  • @Uzi: To read SharedPreferences, you can use the following way; `boolean showInfo = preferences.getBoolean( Constants.PREFERENCES_INFO_SHOWN, false);` – Mudassir Feb 28 '11 at 10:38
  • how to i access a preference file which i have stored on the sd card and what should i look like thanks? – Beginner Feb 28 '11 at 12:30
  • @Uzi: You don't need to access the file directly. Use the above method to read saved data. BTW, preferences are stored as a XML file in you app's com.app.package\shared_prefs folder in the internal storage. – Mudassir Feb 28 '11 at 12:39
  • 4
    Yeh i need a way to store external config data. I dont want them stored internally – Beginner Feb 28 '11 at 12:41
  • @Uzi: What actually do you want to store? – Mudassir Feb 28 '11 at 12:43
  • I want an external file could be xml, java, text. at the moment i need to store a name value, so the application looks in the value for 'name' and the finds bob. In future i can change name to 'fred' and it will call it self fred. – Beginner Feb 28 '11 at 15:02
  • 1
    How can saving key-value data be the answer to the need of having pre-defined data available in the application? It seems to me that shared preferences can hold your data fine, but cannot come pre-loaded with statically "hardcoded" data the developer wishes to include in its application from scratch. – Carlo Moretti Jan 24 '18 at 16:02
2

I met such requirement recently, noting down here, how I did it.

the application to be able to look into a text file on the sd card and pick out certain information that it requires

Requirement:

  1. Configuration value(score_threshold) has to be available at the sdcard. So somebody can change the values after releasing the apk.
  2. The config file must be available at the "/sdcard/config.txt" of the android hardware.

The config.txt file contents are,

score_threshold=60

Create a utility class Config.java, for reading and writing text file.

import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public final class Config {

    private static final String TAG = Config.class.getSimpleName();
    private static final String FILE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/config.txt";
    private static Config sInstance = null;

    /**
     * Gets instance.
     *
     * @return the instance
     */
    public static Config getInstance() {
        if (sInstance == null) {
            synchronized (Config.class) {
                if (sInstance == null) {
                    sInstance = new Config();
                }
            }
        }
        return sInstance;
    }

    /**
     * Write configurations values boolean.
     *
     * @return the boolean
     */
    public boolean writeConfigurationsValues() {

        try (OutputStream output = new FileOutputStream(FILE_PATH)) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("score_threshold", "60");

            // save properties
            prop.store(output, null);

            Log.i(TAG, "Configuration stored  properties: " + prop);
            return true;
        } catch (IOException io) {
            io.printStackTrace();
            return false;
        }
    }

    /**
     * Get configuration value string.
     *
     * @param key the key
     * @return the string
     */
    public String getConfigurationValue(String key){
        String value = "";
        try (InputStream input = new FileInputStream(FILE_PATH)) {

            Properties prop = new Properties();

            // load a properties file
            prop.load(input);
            value = prop.getProperty(key);
            Log.i(TAG, "Configuration stored  properties value: " + value);
         } catch (IOException ex) {
            ex.printStackTrace();
        }
        return value;
    }
}

Create another utility class to write the configuration file for the first time execution of the application, Note: SD card read/write permission has to be set for the application.

public class ApplicationUtils {

  /**
  * Sets the boolean preference value
  *
  * @param context the current context
  * @param key     the preference key
  * @param value   the value to be set
  */
 public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     sp.edit().putBoolean(key, value).commit();
 }

 /**
  * Get the boolean preference value from the SharedPreference
  *
  * @param context the current context
  * @param key     the preference key
  * @return the the preference value
  */
 public static boolean getBooleanPreferenceValue(Context context, String key) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     return sp.getBoolean(key, false);
 }

}

At your Main Activity, onCreate()

if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
           Log.d(TAG, "First time Execution");
           ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
           Config.getInstance().writeConfigurationsValues();
}
// get the configuration value from the sdcard.
String thresholdScore = Config.getInstance().getConfigurationValue("score_threshold");
Log.d(TAG, "thresholdScore from config file is : "+thresholdScore );
Hardian
  • 1,922
  • 22
  • 23