Android共享首选项检索用户名和密码

时间:2012-03-20 07:43:25

标签: android authentication login sharedpreferences

我无法从android的共享偏好中检索用户名和密码。我使用此代码保存用户名并传递

SharedPreferences prefs=getSharedPreferences("File", 0);
    SharedPreferences.Editor e=  prefs.edit();
       e.putString("Email", "example@example.com").putString("Password", "password1");
       e.commit();
       e.putString("Email", "example_2@example.com").putString("Password", "password2");
       e.commit();
       String s=prefs.getString("Email","not found");

但我不知道如何检索用户登录的信息。任何人都可以帮我弄清楚

2 个答案:

答案 0 :(得分:5)

创建共享偏好:

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

从共享偏好中获取价值:

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

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

答案 1 :(得分:0)

您需要为不同的值提供不同的密钥,否则第二封电子邮件将删除第一封电子邮件。将共享首选项视为持久性哈希映射:

   //keep constants, don't use their values. A constant has more meaning
   SharedPreferences 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 file
   String mail1=prefs.getString("Email1","not found");
   String mail2=prefs.getString("Email2","not found");