SharedPreferences返回一个空字符串

时间:2017-10-04 16:17:58

标签: java android

为什么吐司只显示一个空字符串或我输入的任何内容为"默认" getString行上的值

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.stefan.dijeljenepreference", Context.MODE_PRIVATE);
    sharedPreferences.edit().putString("username", "stefan");

    String username = sharedPreferences.getString("username","");
    Toast.makeText(this,"username:" + username, Toast.LENGTH_SHORT).show();
}

1 个答案:

答案 0 :(得分:1)

您应该使用 apply()方法保存您的修改

sharedPreferences.edit().putString("username", "stefan").apply();