I have Activity and service.
Activity store and update data into shared preferences file. I was update the data from Activity and then Service try to retrive changes, but he read the old values.
Code :
Saving\Updating :
@Override
public void save(VolumeBotSettings settings) {
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putInt(START_HOURS, settings.getStartHours());
edit.putInt(START_MINUTES, settings.getStartMinutes());
edit.putInt(END_HOURS, settings.getEndHours());
edit.putInt(END_MINUTES, settings.getEndMinutes());
edit.putInt(RING_VOLUME_LEVEL, settings.getRingVolumeLevel());
edit.putInt(MUSIC_VOLUME_LEVEL, settings.getMusicVolumeLevel());
edit.putInt(NOTIFICATION_VOLUME_LEVEL, settings.getNotificationVolumeLevel());
edit.putInt(ALARM_VOLUME_LEVEL, settings.getAlarmVolumeLevel());
edit.commit();
}
Read :
@Override
public VolumeBotSettings retrieve() {
VolumeBotSettings settings = new VolumeBotSettings();
settings.setStartHours(sharedPreferences.getInt(START_HOURS, UNDEFINED));
settings.setEndHours(sharedPreferences.getInt(END_HOURS, UNDEFINED));
settings.setStartMinutes(sharedPreferences.getInt(START_MINUTES, UNDEFINED));
settings.setEndMinutes(sharedPreferences.getInt(END_MINUTES, UNDEFINED));
settings.setRingVolumeLevel(sharedPreferences.getInt(RING_VOLUME_LEVEL, UNDEFINED));
settings.setMusicVolumeLevel(sharedPreferences.getInt(MUSIC_VOLUME_LEVEL, UNDEFINED));
settings.setNotificationVolumeLevel(sharedPreferences.getInt(NOTIFICATION_VOLUME_LEVEL, UNDEFINED));
settings.setAlarmVolumeLevel(sharedPreferences.getInt(ALARM_VOLUME_LEVEL, UNDEFINED));
if (settings.isNotNull())
return settings;
else
return null;
}
Also i re-init shared preferences before using them.
private static final String VOLUME_BOT_PREFERENCES = "volume_bot_preferences";
public void init(Context context) {
sharedPreferences = context.getSharedPreferences(VOLUME_BOT_PREFERENCES, Context.MODE_PRIVATE);
}
so the step-by-step actions :
Activity call init() method.
Activity call save() method.
Close Activity. Service is running.
Service call init() method.
Service call retrive() method.
And no data was updated. Please help me to understand why.
Note. init(),save(),retrieve() - methods of Singletone class that located in the same app.
Retrived settings is not null.