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中出错,这是NullPointerException导致“boolean isRemember = pref.getBoolean(”remember_password“,false);” 我不知道为什么。如何正确使用getBoolean? 提前谢谢。
答案 0 :(得分:2)
因为pref=null
位于
boolean isRemember = pref.getBoolean("remember_password",false);
在使用之前 initialized
SharedPreferences pref= PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
答案 1 :(得分:1)
您必须创建共享首选项的对象,而不是在您的代码
中使用它 SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
而不是
boolean isRemember = pref.getBoolean("remember_password",false);
答案 2 :(得分: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);