SharedPreferences不会节省价值

时间:2015-05-07 13:51:25

标签: android sharedpreferences

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();
        }
    });

生日值保存得很好,但名称没有。为什么呢?

4 个答案:

答案 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)

替换

editor.apply();

editor.commit();

docs

中详细了解相关信息

答案 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?

的代码

我希望这有帮助!