tuzion
tuzion

Reputation: 27

Android - Is there a way to tell programmatically if a SharedPreferences file is created?

What I want to do is tell my main activity if there is a SharedPreferences file, change a bunch of strings using the values in the file. And if there is no SharedPreferences file created yet, use the default strings that are assigned in the layout (essentially do nothing).

Upvotes: 0

Views: 128

Answers (3)

user2888717
user2888717

Reputation:

You can save preferences with this snippet:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    Editor edit = sp.edit();
    edit.putString(yourkey, yourvalue);
    edit.commit();

And you can fetch them using this:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    sp.getString(yourkey,defaultvalue);

Upvotes: 2

phyllis
phyllis

Reputation: 1

You can try this: PreferenceManager.getDefaultSharedPreferences(this).getString(key, defValue).

Upvotes: 0

Matthew
Matthew

Reputation: 6496

Why not just use the SharedPreferences#getString(String key, String defaultValue) API that let's you specify a default value?

Upvotes: 1

Related Questions