开发者

Android SharedPreferences not accessible in Main, other activities are fine?

I have some data saved to my SharedPreferences but when i try to access it in the Main of my app the SharedPreferences file is empty. If i call the same exact code from any of my other Activities i can access the data just fine. any ideas on what the issue could be???

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
    int test = prefs.getInt("PREF_DIFFICULTY", 0);
}

using the eclipse debugger i can see that the map backing the pref object is empty, but when i view that map from other activities it is full of data...very weird. Here is my manifest just in case it matters.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.dawghouse.dd"
android:versionCode="1" android:versionName="1.0">

<application android:label="@string/app_name" android:icon="@drawable/icon">
    <activity android:name=".activity.Main" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".activity.BlockOutgoing" android:label="@string/outgoingTitle" />
    <activity android:name=".activity.BlockIncoming" android:label="@string/incomingTitle" />
    <activity android:name=".activity.TimeManager" android:label="@string/timeManagerTitle" />
    <activity android:name=".activity.Preferences" android:label="@string/preferences" />
</application>

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
</manifest&g开发者_JAVA技巧t;

thanks in advance!!


Try:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

and see if that works better.


I know the question was already answered correctly, but I figured that I would note for future visitors having the same problem I had: There is a sneaky little .commit() method that has to be tacked onto the end of any SharedPreference edit.


With getPreferences(mode) you get the default preferences, are you sure you've loaded data to it? Better use getSharedPreferences(name, mode) with name will be a defined string constant.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜