Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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??

Any help would be appreciated.

like image 968
UMAR-MOBITSOLUTIONS Avatar asked Jan 28 '10 12:01

UMAR-MOBITSOLUTIONS


1 Answers

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);
like image 117
Dave Webb Avatar answered Oct 12 '22 11:10

Dave Webb