0xDEADBEEF
0xDEADBEEF

Reputation: 590

Remove some SharedPreferences

I am making a simple slashing game and I am saving stuffs like gold in SharedPreferences. How to remove it from SharedPreferences but still be able to call the value of the gold,like Temple run 2 game.

Upvotes: 0

Views: 94

Answers (3)

NateZh
NateZh

Reputation: 81

something like this:

    SharedPreferences sp = getSharedPreferences("your sp name", Context.MODE_PRIVATE);
    sp.edit().remove("gold").commit();// remove gold
    sp.edit().clear().commit();//remove all 

Upvotes: 0

Simon
Simon

Reputation: 1190

You can write to Shared Preferences

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

and then read from Shared Preferences

SharedPreferences sharedPref = 
getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

And also dont forget to get a handle

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Upvotes: 0

Surya Prakash Kushawah
Surya Prakash Kushawah

Reputation: 3201

To remove specific values: SharedPreferences.Editor.remove() followed by a commit()

To remove them all SharedPreferences.Editor.clear() followed by a commit()

If you don't care about the return value and you're using this from your application's main thread, consider using apply() instead.

Upvotes: 1

Related Questions