I am creating an application which connects to the server using username/password and I would like to enable the option \"Save password\" so the user wouldn\'t have to type
This is a supplemental answer for those arriving here based on the question title (like I did) and don't need to deal with the security issues related to saving passwords.
User settings are generally saved locally in Android using SharedPreferences
with a key-value pair. You use the String
key to save or look up the associated value.
String key = "myInt";
int valueToSave = 10;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(key, valueToSave).commit();
Use apply()
instead of commit()
to save in the background rather than immediately.
String key = "myInt";
int defaultValue = 0;
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
int savedValue = sharedPref.getInt(key, defaultValue);
The default value is used if the key isn't found.
Rather than using a local key String in multiple places like I did above, it would be better to use a constant in a single location. You could use something like this at the top of your settings activity:
final static String PREF_MY_INT_KEY = "myInt";
I used an int
in my example, but you can also use putString()
, putBoolean()
, getString()
, getBoolean()
, etc.
See the documentation for more details.
There are multiple ways to get SharedPreferences. See this answer for what to look out for.