I'm trying to save information on an Android app I've made. I want to save a name, "Robert". For this I've been looking into Shared Preferences and I can't find a tutorial that explains how to create SharedPreferences.
All tutorials start like this:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences are created like this:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit(); editor.putString("name", "Robert"); editor.commit(); //Or use editor.apply()
Then you get them again like this:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
So, the getString() gets the value you stored before, and returns the default value if you haven't stored a string for 'name' yet.
The object you store is saved in the system, and is constantly available to be grabbed.
UPDATE: The getSharedPreferences() method returns a SharedPreferences.Editor interface. According to the android docs
Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
UPDATE 2: This answer contains more info on the storage of SharedPreferences.