Nikocevic Stefan
Nikocevic Stefan

Reputation: 31

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

Upvotes: 0

Views: 176

Answers (1)

an_droid_dev
an_droid_dev

Reputation: 1136

You should save your edits using apply() method like this

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

Upvotes: 1

Related Questions