【问题标题】:Android shared preferences retrieve username and passwordAndroid共享首选项检索用户名和密码
【发布时间】:2012-04-04 16:41:17
【问题描述】:

我无法从 android 的 sharedpreferences 中检索用户名和密码。我使用此代码保存用户名并通过

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");

但我不知道如何检索用户登录信息。谁能帮我弄清楚

【问题讨论】:

  • Java Hashmap的简单概念,查一下。

标签: android authentication login sharedpreferences


【解决方案1】:

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

   //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");

【讨论】:

    【解决方案2】:

    创建分享偏好:

    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);
    

    【讨论】:

    • 是的,是的,我刚刚弄明白了。非常感谢 :) 这是我一直在寻找的解决方案!
    • 好的,亲爱的,如果这对您有用,请接受答案..所以它也会对其他人有所帮助..
    • 我在同一个包中有一个司机应用和一个骑手应用。我正在尝试从驱动程序应用程序中获取当前的乘客 ID。我按照您上面所做的那样做了,但是 RiderId 被返回为 null?我做错了什么?
    • App A: // .. 创建一个共享首选项 - 与驱动程序共享当前用户 ID String currentRider = FirebaseAuth.getInstance().getCurrentUser().getUid(); SharedPreferences sp = getSharedPreferences("Current_User", 0); SharedPreferences.Editor ed = sp.edit(); ed.putString("骑手", currentRider ); ed.commit(); App B: // .... 从共享偏好中获取价值 (RiderActivity)..... SharedPreferences sp1 = this.getSharedPreferences("Current_User", 0); RiderId = sp1.getString("骑手", null); Log.d("RIDERID", "RiderId = " +riderId);
    猜你喜欢
    • 2015-10-11
    • 2012-09-03
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多