Skip to content Skip to sidebar Skip to footer

Android Shared Preferences Retrieve Username And Password

Im having trouble with retrieving username and password from android's sharedpreferences. I use this code to save the username and pass SharedPreferences prefs=getSharedPreference

Solution 1:

Create Share Preference:

SharedPreferences sp=getSharedPreferences("Login", 0);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString("Unm",Value );              
Ed.putString("Psw",Value);   
Ed.commit();

Get Value from Share preference:

SharedPreferences sp1=this.getSharedPreferences("Login",null);

String unm=sp1.getString("Unm", null);       
String pass = sp1.getString("Psw", null);

Solution 2:

You need to give different keys for different values, otherwise the second email will erase the first one. See shared preferences as a persistent hashmap :

//keep constants, don't use their values. A constant has more meaningSharedPreferences prefs=getSharedPreferences("File", MODE_PRIVATE );
   SharedPreferences.Editor e=  prefs.edit();
   //keys should be constants as well, or derived from a constant prefix in a loop.
   e.putString("Email1", "example@example.com").putString("Password1", "password1");
   e.putString("Email2", "example_2@example.com").putString("Password2", "password2");
   //commit once, not twice
   e.commit();

   //not found should be a constant in a xml resource fileString mail1=prefs.getString("Email1","not found");
   String mail2=prefs.getString("Email2","not found");

Post a Comment for "Android Shared Preferences Retrieve Username And Password"