What is the most appropriate way to store user settings in Android application

后端 未结 14 2085
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 05:38

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

14条回答
  •  粉色の甜心
    2020-11-22 06:24

    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.

    How to use Shared Preferences

    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.

    Write to Shared Preferences

    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.

    Read from Shared Preferences

    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.

    Notes

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

提交回复
热议问题