Vic Vuci
Vic Vuci

Reputation: 7051

How do I change the value of a SharedPreference without going into the preference screen?

I have a string I want to store in my SharedPreferences. Is there some kind of setString I could do to accomplish this?

Upvotes: 0

Views: 65

Answers (3)

ilnus
ilnus

Reputation: 11

And you can do everything in the same line, there's no need to declare editor

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.edit().putString("username", "myUsername").commit();

And don't forget the commit!

Upvotes: 1

Vikram Singh
Vikram Singh

Reputation: 1806

Try this.

    SharedPreferences prefs = getSharedPreferences("PreferenceFileName", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("StringNameToBeStored", "value");
    editor.commit();

Upvotes: 1

harmjanr
harmjanr

Reputation: 937

You mean something like this?

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username", "myUsername");
editor.commit();

You can make changes in the SharedPreferences, and commit the changes after you are done.

Upvotes: 1

Related Questions