2015-06-25 53 views
0
public class LoginActivity extends BaseActivity{ 
    private SharedPreferences pref; 
    private SharedPreferences.Editor editor; 

    private EditText accountEdit; 

    private EditText passwordEdit; 

    private Button login; 
    private CheckBox rememberPass; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.login); 
     accountEdit =(EditText)findViewById(R.id.account); 
     passwordEdit = (EditText)findViewById(R.id.password); 
     rememberPass=(CheckBox)findViewById(R.id.remember_pass); 

     login = (Button)findViewById(R.id.login); 
     editor.putBoolean("remember_password",false); 
     boolean isRemember = pref.getBoolean("remember_password",false); 
     if(isRemember){ 
      String account = pref.getString("account", ""); 
      String password =pref.getString("password", ""); 
      accountEdit.setText(account); 
      passwordEdit.setText(password);   
      rememberPass.setChecked(true); 
     } 

     login.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       String account =accountEdit.getText().toString(); 
       String password = passwordEdit.getText().toString(); 

       if (account.equals("admin")&& password.equals("123456")) 
       { editor = pref.edit(); 
        if(rememberPass.isChecked()) 
        { 
         editor.putBoolean("remember_password",true); 
         editor.putString("account",account); 
         editor.putString("password",password); 
        } 
        else 
        { 
         editor.clear(); 
        } 
        editor.commit(); 

        Intent intent = new Intent(LoginActivity.this,MainActivity.class); 
        startActivity(intent); 
        finish(); 
       } 
       else 
       { 
        Toast.makeText(LoginActivity.this,"account for password is invalid", 
          Toast.LENGTH_LONG).show(); 
       }    
      } 
     }); 

    } 
} 

我使用Eclipse編寫android.I得到了在logcat的一個錯誤,這是「布爾isRemember = pref.getBoolean NullPointerException異常的原因(」 remember_password「假);」 我不知道爲什麼。如何正確使用getBoolean? 在此先感謝。使用sharedPreference保存賬號和密碼

回答

2

因爲pref=null

boolean isRemember = pref.getBoolean("remember_password",false); 

initialized之前所使用的

SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(LoginActivity.this); 
1

你必須創建共享偏好的對象比你可以在你的代碼中使用它

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 

比使用

boolean isRemember = pref.getBoolean("remember_password",false); 
1

使用這個簡單的方式來使用prefrences

 private SharedPreferences getPrefs; 

    //in OnCreate 
    getPrefs = PreferenceManager.getDefaultSharedPreferences(Activity_Name.this); 

    //At insertion value 
    getPrefs.edit().putBoolean("Key_Name", false).commit(); 

    //At fetching Values 
    boolean a = getPrefs.getBoolean("Key_Name", false);