0

I'm having a sync adapter in my android app and I'm saving few data in the shared preferences.

Let me explain by taking example as timestamp, in sync adapter I'm storing the timestamp and when I open/use my android app the data is still showing the old data.

I'm using the below code,

public void saveTimeStamp(long timestamp) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putLong("timestamp", timestamp);
        editor.apply();
    }

public long getLoginTimestamp() {
        return sharedPreferences.getLong("timestamp", 0);
    }

I tried calling the same method from the app and it is updating. Even I debugged and checked it is calling the above method from sync adapter too but the data is not updating.

In sync adapter I checked logging the data, it is logged correctly but in the app it is not reflected. I'm thinking it is taking separate set of preferences for sync adapter and app since both will be under different process

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Praveen
  • 465
  • 5
  • 13
  • How are you getting the `SharedPreferences` object in the sync adapter, and how in the app? – Mike M. Jan 23 '18 at 06:59
  • @MikeM. I'm having a singleton class and I'm calling that class by passing a context. I'm using the same class in both the app and the sync adapter service – Praveen Jan 23 '18 at 07:01
  • @MikeM. I tried debugging and logging. Now I came to know that for sync adapter it is taking separate preferences and for app it is taking separate preferences. How can I handle this – Praveen Jan 23 '18 at 07:45
  • 1
    Have a look at this post: https://stackoverflow.com/q/26408622. – Mike M. Jan 23 '18 at 07:57
  • @MikeM. Thanks, it's working fine now – Praveen Jan 23 '18 at 08:10

1 Answers1

0

I got the solution,

I was using

sharedPreferences = context.getSharedPreferences(
                    context.getString(R.string.preference_name),
                    Context.MODE_PRIVATE);

Now I changed to

sharedPreferences = context.getSharedPreferences(
                    context.getString(R.string.preference_name),
                    Context.MODE_MULTI_PROCESS);

Sync adapter and the app will be running in the different process. If we have to use the same preferences then we have to pass Context.MODE_MULTI_PROCESS instead Context.MODE_PRIVATE

Praveen
  • 465
  • 5
  • 13