how to use getSharedPreferences in android
First get the instance of SharedPreferences using
SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Now to save the values in the SharedPreferences
Editor edit = userDetails.edit();edit.putString("username", username.getText().toString().trim());edit.putString("password", password.getText().toString().trim());edit.apply();
Above lines will write username and password to preference
Now to to retrieve saved values from preference, you can follow below lines of code
String userName = userDetails.getString("username", "");String password = userDetails.getString("password", "");
(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)
//Set PreferenceSharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);SharedPreferences.Editor prefsEditor; prefsEditor = myPrefs.edit(); //strVersionName->Any value to be stored prefsEditor.putString("STOREDVALUE", strVersionName); prefsEditor.commit();//Get Preferenece SharedPreferences myPrefs; myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE); String StoredValue=myPrefs.getString("STOREDVALUE", "");
Try this..
If someone used this:
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
PreferenceManager is now depricated, refactor to this:
val sharedPreferences = context.getSharedPreferences(context.packageName + "_preferences", Context.MODE_PRIVATE)