final SharedPreferences sp = getSharedPreferences("birthday", 0);
final SharedPreferences sp2 = getSharedPreferences("name", 0);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sp.edit();
editor.putString("birthday", birthday.getText().toString());
editor.apply();
SharedPreferences.Editor editor2 = sp2.edit();
editor2.putString("name", name.getText().toString());
editor2.apply();
Toast.makeText(SettingsActivity.this, "Changes saved.", Toast.LENGTH_SHORT).show();
}
});
生日值保存得很好,但名称没有。为什么呢?
答案 0 :(得分:2)
试试这个:
SharedPreferences.Editor editor = sp.edit();
editor.putString("birthday", birthday.getText().toString());
editor.putString("name", name.getText().toString());
editor.commit();
答案 1 :(得分:1)
final SharedPreferences sp = getSharedPreferences("data", 0);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sp.edit();
editor.putString("birthday", birthday.getText().toString());
editor.putString("name", name.getText().toString());
editor.commit();
Toast.makeText(SettingsActivity.this, "Changes saved.", Toast.LENGTH_SHORT).show();
}
});
修正了问题!不得不只使用一个SharedPreferences实例而不是两个。
答案 2 :(得分:0)
答案 3 :(得分:0)
这是我在应用中存储值时的方法:
save.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("birthday", birthday.getText().toString());
editor.putString("name", name.getText().toString());
editor.apply();
}
});
保存到首选项时遇到的问题是我如何实际获取SharedPreferences的实例;
请您分享用于实例化sp?
的代码我希望这有帮助!