How do I get SharedPreference object in FragmentStatePagerAdapter?

这一生的挚爱 提交于 2019-12-08 13:15:03

问题


I wanna add an integer dynamically in the getCount() method of custom pager adapter that obviously extends FragmentStatePagerAdapter.

return some integer value;

I have a counter saved in Shared Preference object and it gets updated with clicks on star images. I wanna return the updated counter value in the mentioned method, so I can generate that many swipe views but the problem is I unable to get Shared Preference object there. This is the only obstacle between my app and the play store, I've been developing it for like month or two. So please gimme suggestion on this issue I'm facing. Thanks in advance guys!


回答1:


https://developer.android.com/training/basics/data-storage/shared-preferences.html

https://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String, int)

Set your value onPause() and onStop and read your value onResume and onCreate.

You need to set a final string which would be your SharedPreferences filename.

Get your value and increment

Writing:

SharedPreferences sharedPref = getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_value), newValue);
editor.commit();

Reading:

SharedPreferences sharedPref = getActivity().getSharedPreferences(YOUR_FINAL_STRING, Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_value_default);
long value = sharedPref.getInt(getString(R.string.saved_value), defaultValue);

First read the value and set it to a variable in shared preferences.

Increment the same value onPause or onStop.



来源:https://stackoverflow.com/questions/44051292/how-do-i-get-sharedpreference-object-in-fragmentstatepageradapter

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