Accessing preferences / configuration / settings from Android is actually pretty straightforward as long as you are in an Activity. To read:
// PREFS_FILENAME = "nameOfPrefsFile"; SharedPreferences pref = getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE); String string = pref.getString("key", "default"); // 1 is the default if key isn't set int intValue = pref.getInt("intKey", 1); // and so on
SharedPreferences is the key class. To write, you also need the SharedPreferences.Editor class, as follows:
// PREFS_FILENAME = "nameOfPrefsFile"; SharedPreferences pref = getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putString("key", "value"); editor.putInt("intKey", 5); // Until you call commit, the changes will not // be written, so don't forget this step editor.commit();
In general however, you will need access to settings in more than one activity and it seems a bit wasteful to get these bits littered through the application. Since I am lazy and like to write things just once, I separated all the prefs stuff into one class called Settings.