I have a minimal program that does little more than let me set two preferences (an int and a String) using Android's PreferenceActivity
. So I have an xml file that defines my preferences, and an activity that extends PreferenceActivity
. My main activity has an options menu that launches my preference activity. All of that works great. I can set my preferences and the values are retained during and after my program executes.
Now, in my main activity I want to retrieve those preferences. Should be easy, right? Here's the code from every sample I've ever seen:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int intSetting = prefs.getInt("intSetting", 0);
String strSetting = prefs.getString("strSetting", "");
Problem is, if I break at the getInt()
call and step over, my stack looks like this and the app will crash if I continue:
Thread [<3> main] (Suspended)
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2494
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2512
ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119
ActivityThread$H.handleMessage(Message) line: 1863
ActivityThread$H(Handler).dispatchMessage(Message) line: 99 Looper.loop() line: 123
ActivityThread.main(String[]) line: 4363 Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method] Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 860 ZygoteInit.main(String[]) line: 618 NativeStart.main(String[]) line: not available [native method]
I've tried variations on the parameter passed to getDefaultSharedPreferences(), including:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
...and probably some others in different context (i.e. when accessing preferences from my main activity vs. another activity vs. some function in a class that isn't an activity. The result is always the same.
I've read a dozen Q&A posts on the Web from others with this problem who have solved it by writing code identical to mine, so I don't expect there's a solution but if anyone has any ideas, let me know.