简体   繁体   中英

SharedPreferences lost when onCreate is called again

I have the following situation:

One activity that is updated from a service. When the update is made, some preferences are written. Everything fine so far. When the activity is not visible and the service decides to do an update, I get a notification. Clicking on this notification opens the activity where I expect to find the previously stored preferences, but nothing is there.

I saw that when clicking on the notification the onCreate() method of the activity is called and this is where I create an arrayadapter which contains the preferences, unfortunately the preferences are somehow not there.

Please keep in mind that:

  • I use commit() when I update the preferences

  • I access the SharedPreferences this way (when reading and when writing):

    SharedPreferences sharedPref = context.getSharedPreferences( SHARED_PREF_FILE, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);

where SHARED_PREF_FILE is a constant. While debugging I found out that the sharedPref object is pointing to the same xml file (/data/data/........xml), so this should be okay.

Best regards

Edit (some code):

I have a class ( PrefManager ) managing the SharedPreferences:

public static Set<String> retrieveData(Context context) {
    SharedPreferences sharedPref = context.getSharedPreferences(
            SHARED_PREF_FILE, Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);
    return sharedPref.getStringSet(MY_KEY,
            new HashSet<String>());
}

In the Activity's onCreate() I have this:

myAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, PrefManager.retrieveData(this));

Answering my own question, in case someone stumbles upon this:

I was able to make it work by adding this to the intent that was used for the creation of the notification:

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM