我正在尝试使用sharedpreferences保存用户凭据,我这样做但是它无法正常工作
public class MainActivity extends Activity {
public EditText UserName;
public EditText Password;
public Button mButton;
public String user_name;
public String pass_word;
public CheckBox mCheckSavePassword;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UserName = (EditText) findViewById(R.id.textUserName);
Password = (EditText) findViewById(R.id.textPassword);
mButton = (Button) findViewById(R.id.buttonLogin);
mCheckSavePassword = (CheckBox) findViewById(R.id.checkSavePassword);
mCheckSavePassword = (CheckBox) findViewById(R.id.checkSavePassword);
SharedPreferences.Editor preferencesEditor = preferences.edit();
preferencesEditor.putString("prefUserName", user_name);
if(mCheckSavePassword.isChecked()) {
preferencesEditor.putString("prefPassword", pass_word);
}
preferencesEditor.putBoolean("prefSavePassword", mCheckSavePassword.isChecked());
preferencesEditor.apply();
}
答案 0 :(得分:2)
您正在保存空值 - 首次创建活动时,user_name
和pass_word
尚未初始化。
onCreate
您应该 阅读 这些首选项的值,并使用这些值更新EditTexts。保存应该是由于某些用户交互的结果,例如按下按钮时。