2

In my android service I have action user present registered which writes a String value to default shared preference. Meanwhile I have another function in the service which writes a Hashset to shared preference. I have used commit in both cases.

On user present action :

PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putString("abc", udata).commit();

On onother function :

if(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit().putStringSet("si",ssetdata).commit())

Some times second writing fails why ? Is it because

"Note that when two editors are modifying preferences at the same time, the last one to call commit wins. "

Leon Joosse
  • 959
  • 1
  • 7
  • 17
Senthil Kumar
  • 299
  • 1
  • 4
  • 14
  • I removed the string set , commited and then added again. It worked all time. http://stackoverflow.com/questions/16820252/android-string-set-preference-is-not-persistent?lq=1 question answered by http://stackoverflow.com/users/1150712/zhangxaochen helped me. – Senthil Kumar Oct 24 '14 at 15:29

3 Answers3

2

Use apply for the first and commit to the second might help like related below:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

Read more here

Zsolt Boldizsar
  • 2,447
  • 2
  • 27
  • 37
1

Is your service running in a separate process? (see the android:process attribute in AndroidManifest.xml)

If so, you have to open the SharedPreferences using MODE_MULTI_PROCESS.

Randy Sugianto 'Yuku'
  • 71,383
  • 57
  • 178
  • 228
0

try to call your SharedPreference just once, and then use editor to commit your data:

                SharedPreference SP;
                SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
                editor = SP.edit();

                //...
                    editor.putString("abc", udata);
                    editor.commit();
                //...
                    editor.putStringSet("si",ssetdata)
                    editor.commit()
PedroHawk
  • 622
  • 5
  • 19