Remove some SharedPreferences

2019-09-06 21:38发布

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.

3条回答
干净又极端
2楼-- · 2019-09-06 21:46

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);
查看更多
看我几分像从前
3楼-- · 2019-09-06 21:51

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-09-06 22:04

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 
查看更多
登录 后发表回答