简体   繁体   中英

SharedPreferences returning an empty string

Why does the toast only show an empty string or whatever I input as the "default" value on the getString line

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

您应该使用如下的apply()方法保存所做的编辑

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM