I'm storing some values in my PreferencesFragment in this way:
// SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = getPreferenceScreen().getSharedPreferences();
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
Then, I want to read the preferences in a non activity class:
// SharedPreferences prefs = ActivityHandler.getCurrentActivity().getSharedPreferences("Test", 0);
SharedPreferences prefs = ActivityHandler.getCurrentActivity().getPreferences(0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
I've tried also the uncommented code, but I get always 0 for both values.
You are doing it wrong. Each time you are getting a different shared preference. Use this code:
For storing value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
SharedPreferences.Editor edit = prefs.edit();
edit.putInt(getString(R.string.valOneKey), 100);
edit.putInt(getString(R.string.valTwoKey), 200);
edit.commit();
For fetching value:
SharedPreferences prefs = getActivity().getSharedPreferences("Test", 0);
int valOne = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valOneKey), 0);
int valTwo = prefs.getInt(ActivityHandler.getCurrentActivity().getString(R.string.valTwoKey), 0);
Hope this will help you.
Try this
SharedPreferences sharedPref = getSharedPreferences("my_pref", Context.MODE_MULTI_PROCESS);
Editor editor = sharedPref.edit();
editor.putInt("KEY", VAL);
..
..
editor.commit();
SharedPreferences sharedPref = getSharedPreferences(
"my_pref", Context.MODE_MULTI_PROCESS);
int size = sharedPref.getInt("KEY", default_VAL);
This will be helpful...thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.