2013-05-31 65 views
0

我想创建一个应用程序,该应用程序将在用户下次使用此应用程序时保存密码。我有我的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; 
      } 

} 
+0

'...但密码不对想要保存.'。那么它说什么?你怎么知道它不能保存? –

回答

0

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

如果没有特殊需要与几个共享偏好文件的工作,我会建议你使用你的应用程序的共享偏好的默认实例:PreferenceManager.getDefaultSharedPreferences(this)