using Raghav's I created a complete working example:
public class AppCache {
public static HashMap<String, String> hashMap = null;
/* REPOSITORY NAME */
public static final String REPOSITORY_NAME = "HMIAndroid_System_Settings";
/* SETTINGS */
public static final String SETTING_PLANNED = "DATA_PLANNED";
public static final String SETTING_ACTUAL = "DATA_ACTUAL";
public static final String SETTING_ETA = "DATA_ETA";
public static final String SETTING_OR = "DATA_OR";
public static final String SETTING_LINEID = "LINEID";
public static final String SETTING_SERVERIP = "SERVERIP";
public static void LoadSettings(Context context) {
SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
hashMap = (HashMap<String, String>) pref.getAll();
if(hashMap == null) {
hashMap = new HashMap<String, String>();
}
}
public static void SaveSettings(Context context) {
if(hashMap == null) {
hashMap = new HashMap<String, String>();
}
//persist
SharedPreferences pref = context.getSharedPreferences(REPOSITORY_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
for (String s : hashMap.keySet()) {
editor.putString(s, hashMap.get(s));
}
editor.commit();
}
}
Then in your onCreate load it:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//load settings
AppCache.LoadSettings(getApplicationContext());
Log.d("onCreate","My LineID=" + AppCache.hashMap.get(AppCache.SETTING_LINEID));
Log.d("onCreate","Dest ServerIP=" + AppCache.hashMap.get(AppCache.SETTING_SERVERIP));
}
at any time anywhere in your app update settings:
AppCache.hashMap.put(AppCache.SETTING_LINEID, "1");
AppCache.hashMap.put(AppCache.SETTING_SERVERIP, "192.168.1.10");
in your onDestroy save settings to cache:
@Override
protected void onDestroy() {
//save settings
AppCache.SaveSettings(getApplicationContext());
}