user3104719 user3104719 - 18 days ago 5
Android Question

Android Shared preferences example

I want to retrieve user input in an app for later usage.

For example, the user is prompted to enter all 7 days of the week and types into the editText box "Monday", "Tuesday" etc. Then later in the app a question will come up and ask what is your favorite day? And the spinner will show a dropdown list of the days they entered for the user to pick from.

I guess shared preferences would work for this, but I cannot find a good example to give me a starting place. Any help would be appreciated.

Answer

Setting values in Preference:

// 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:

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.
}

more info:

Using Shared Preferences

Shared Preferences