为什么输入的密码不能在我的IF语句中进行比较?(共享偏好)

时间:2013-10-21 23:31:59

标签: java android if-statement sharedpreferences

我正在完成我的任务,我不确定为什么If语句没有将密码存储在shredpreference中并与此页面中输入的密码进行比较。我真的想知道哪些变量或特定部分我做错了?请帮帮忙!

package com.wheresmyphone;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Check_Activity extends Activity {

public static final String passwdfile = "passwd";

String passwd;
private static final String PREF_PASSWORD = "PassWord";
protected EditText PassWordField;
protected Button EnterButton;

SharedPreferences sharedpref;   
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_check_);

    final EditText userpassword = (EditText)findViewById(R.id.editText1);

    Button b = (Button)findViewById(R.id.button1);

    sharedpref = getSharedPreferences(passwdfile, 0);





    b.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            String passwd = userpassword.getText().toString();
            SharedPreferences passwdfile = getSharedPreferences("passwd",0);
            SharedPreferences.Editor editor = sharedpref.edit();
            editor.putString(PREF_PASSWORD, passwd);
            editor.commit();
            //commit data
            String storedpassword = passwdfile.getString(passwd, null) ;  


            if (passwd.equals(storedpassword)) {

            startActivity(new Intent(Check_Activity.this, MainActivity.class));


                finish();




            }else {
                Toast.makeText(Check_Activity.this, "Incorrect Password, Please try again!", Toast.LENGTH_LONG).show();
                return;
            }

        }



        });
}

1 个答案:

答案 0 :(得分:2)

您正在尝试使用错误的密钥检索存储的密码。也就是说,改变:

String storedpassword = passwdfile.getString(passwd, null);

要:

String storedpassword = passwdfile.getString(PREF_PASSWORD, null);