在android studio中使用共享首选项实现用户帐户

时间:2016-09-13 17:17:10

标签: java android

我试图在android studio中通过shared preferences实现用户帐户。我计划通过使用String数组来实现它,这就是我所拥有的。

注册用户名和密码

   public void registerUser(View view){
    SharedPreferences users = getSharedPreferences("usernames", Context.MODE_PRIVATE);
    SharedPreferences pass = getSharedPreferences("passwords", Context.MODE_PRIVATE);
    SharedPreferences.Editor edit = users.edit();
    SharedPreferences.Editor editpass = pass.edit();
    edit.putInt("array_size", Username.length);
    for(int i=0;i<Username.length; i++)
        edit.putString("array_" + i, Username[i]);
    editpass.putInt("array_size", Passwords.length);
    for(int i=0;i<Passwords.length; i++)
        edit.putString("array_" + i, Passwords[i]);
    edit.commit();
    editpass.commit();
    Toast.makeText(this, "Saved both user and pass", Toast.LENGTH_SHORT).show();
}

我尝试在登录页面上使用此代码验证它,

 public void login(View view) {
    SharedPreferences users = getSharedPreferences("usernames", Context.MODE_PRIVATE);
    SharedPreferences pass = getSharedPreferences("passwords", Context.MODE_PRIVATE);
    CurrentUser = tvuser.getText().toString();
    CurrentPassword = tvpass.getText().toString();
    int size = users.getInt("array_size", 0);
    String[] array = new String[size];
    String cuser;
    String cpass;
    for (int i = 0; i < size; i++) {
        cuser = users.getString("array_" + i, null);
        if (cuser.equals(CurrentUser)) {
            cpass = pass.getString("array_" + i, null);
            if (cpass.equals(CurrentPassword)) {
                Intent in = new Intent(this, UserActivity.class);
                startActivity(in);
            } else {
                Toast.makeText(this, "Invalid Username or Password!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

注册正在运行,但登录无效。 任何帮助,将不胜感激。我需要通过共享偏好来做到这一点。我知道有更简单的方法来使用数据库。在此先感谢。

0 个答案:

没有答案