Remove some SharedPreferences

若如初见. 提交于 2019-12-25 01:38:45

问题


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.


回答1:


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.




回答2:


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:


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 


来源:https://stackoverflow.com/questions/40978948/remove-some-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!