Blog Of Sem: android studio shared preferences

android studio shared preferences

Define some statics to store the preference file name and the keys you're going to use:
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
You'd then save the username and password as follows:
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
        .edit()
        .putString(PREF_USERNAME, username)
        .putString(PREF_PASSWORD, password)
        .commit();
So you would retrieve them like this:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);   
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);

if (username == null || password == null) {
    //Prompt for username and password
}
Alternatively, if you don't want to name a preferences file you can just use the default:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);