1 |
String sPNotes = getPreferences(Context.MODE_PRIVATE).getString("NOTES", "EMPTY"); |
1 2 3 4 5 6 7 8 9 10 |
// 1. Called before Android kills an application, but doesn't protect you // if the user kills the app or restarts the device @Override protected void onSaveInstanceState(Bundle outState) { // Save the value in the EditText using the key NOTES outState.putString("NOTES","Your string"); super.onSaveInstanceState(outState); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// 2. Will save key value pairs to SharedPreferences private void saveSettings(){ // SharedPreferences allow you to save data even if the user kills the app // MODE_PRIVATE : Preferences shared only by your app // MODE_WORLD_READABLE : All apps can read // MODE_WORLD_WRITABLE : All apps can write // edit() allows us to enter key vale pairs SharedPreferences.Editor sPEditor = getPreferences(Context.MODE_PRIVATE).edit(); // Add the key "NOTES" and assign it to the value sPEditor.putString("NOTES", notesEditText.getText().toString()); // Save the shared preferences sPEditor.commit(); } |
=============================================
Setting values in Preference:
1 2 3 4 5 6 |
// MY_PREFS_NAME - a static String variable like: //public static final String MY_PREFS_NAME = "MyPrefsFile"; SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "Elena"); editor.putInt("idName", 12); editor.commit(); |
Retrieve data from preference:
1 2 3 4 5 6 |
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs.getString("text", null); if (restoredText != null) { String name = prefs.getString("name", "No name defined");//"No name defined" is the default value. int idName = prefs.getInt("idName", 0); //0 is the default value. } |
Android SharedPreferences in Fragment
1 2 |
// this = your fragment SharedPreferences preferences = this.getActivity().getSharedPreferences("pref", Context.MODE_PRIVATE); |