0

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();
}
3
  • Missing apply call after the putString Commented Oct 4, 2017 at 16:20
  • you didn't use apply() or commit() after edit that's why Commented Oct 4, 2017 at 16:21
  • Awesome, that was it, thanks. Commented Oct 4, 2017 at 16:21

1 Answer 1

1

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

sharedPreferences.edit().putString("username", "stefan").apply();
Sign up to request clarification or add additional context in comments.

1 Comment

@NikocevicStefan glad to help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.