Listing out some useful Shared Preferences snippets for easy references
public static final String MyPREFERENCES = "MyPrefs" ; //name to save Shared Preferences xml file
String currentmode = ""; //default current mode to start App
//find the App's Shared Preferences. If it doesn't exist, create one. Name it "setting"
SharedPreferences setting = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
//debug : used to shared preferences
/* Editor editor = setting.edit();
editor.clear();
editor.commit(); */
//check the last saved mode of operation. load it if it existed
public void checkMode(){
if (setting.contains("savedmode")){
currentmode = (setting.getString("savedmode",""));
Toast.makeText(getApplicationContext(),"Loading last saved mode of operation", Toast.LENGTH_SHORT).show();
} else {
//no setting saved for mode. Save convenient mode by default
currentmode = "convenient";
Editor editor = setting.edit();
editor.putString("savedmode", currentmode);
editor.commit();
Toast.makeText(getApplicationContext(),"No mode found in the setting", Toast.LENGTH_SHORT).show();
}
}
//debug : to show all data stored in Shared Preferences
/*Map<string> keys = setting.getAll();
for(Map.Entry<string> entry : keys.entrySet()){
Log.d("map values",entry.getKey() + ": " + entry.getValue().toString());
}*/
//mode toggling method for ToggleButton. Save the adjusted current mode to Shared Preferences
public void ToggleMode(View view){
ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleMode);
boolean on = toggle.isChecked();
if (on){
currentmode = "convenient";
Editor editor = setting.edit();
editor.putString("savedmode", currentmode);
editor.commit();
Toast.makeText(getApplicationContext(),"Mode changed to Convenient", Toast.LENGTH_SHORT).show();
} else {
currentmode = "secured";
Editor editor = setting.edit();
editor.putString("savedmode", currentmode);
editor.commit();
Toast.makeText(getApplicationContext(),"Mode changed to Secured", Toast.LENGTH_SHORT).show();
}
};