使用“共享首选项”设置和保存密码

时间:2013-05-31 00:16:33

标签: android if-statement passwords sharedpreferences

我想创建一个应用程序,它将在下次用户想要使用此应用程序时保存密码。我的If语句有效,但密码不想保存。这是一个任务,我尝试了一些东西,但似乎没有任何工作。请帮忙!

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

public class WheresMyPhoneActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    private Button start;
    private EditText pword;
    private EditText confirm;
    SharedPreferences myFolder; 
    public final String filename = "PasswordFile";

        @Override
        public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        start = (Button)findViewById(R.id.btnStart);
        pword = (EditText)findViewById(R.id.edtPassword);
        confirm = (EditText)findViewById(R.id.edtConfirm);
        myFolder = getSharedPreferences(filename, 0);

        start.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
            String pass = pword.getText().toString();
            String conf = confirm.getText().toString();

            //Check that user typed in a password
            if(pass.length()<6){
                Toast.makeText(this, "Password must be at least 6     characters long", Toast.LENGTH_SHORT).show();
                pword.setText("");
                confirm.setText("");
                pword.requestFocus();
                return;
            }
            //Make sure two fields match
            if(pass.equals(conf)){
                //fields match, store configuration in shared preferences
                Editor passwdfile = getSharedPreferences("passwd", 0).edit();
                passwdfile.putString("passwd",pass);
                passwdfile.commit();
                finish();
                startActivity(new Intent(WheresMyPhoneActivity.this, Home.class));

            }else{//password mismatch - start over
                Toast.makeText(this, "Passwords must match", Toast.LENGTH_SHORT).show();
                pword.setText("");
                confirm.setText("");
                pword.requestFocus();
                return;
            }

}

1 个答案:

答案 0 :(得分:0)

您确定不会错过匹配的共享首选项文件名吗? 我看到你有一个myFolder = getSharedPreferences(filename, 0); filename = "PasswordFile"。另一方面,您将密码保存到另一个名为passwd的共享首选项文件:getSharedPreferences("passwd", 0)

如果您没有特定需要使用多个共享偏好设置文件,我建议您使用应用的默认共享偏好设置实例:PreferenceManager.getDefaultSharedPreferences(this)