How do I implement a 'Remember me' function in an Android Activity?

前端 未结 2 1171
野的像风
野的像风 2020-12-12 19:59

I have a username, password, and checkbox (next to the text \'remember me\').

How do I to implement a remember me function to keep username and password data??

2条回答
  •  离开以前
    2020-12-12 20:36

    You can save values associated with your application using 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);
    

提交回复
热议问题