I have used a Broadcast receiver to change the value of a variable inside my fragment every 24 hours.
Since the value of the variable gets reinitialized to previous initialization when the fragment restarts I have used shared preferences to save the value every time so that it does not reinitialize again and again.
The problem is that the value is changed once and is not updating again. so if the value is 10 it changes to 11 but then does not go to 12.
This is the broadcast receiver
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String intentImageName = intent.getStringExtra("imageName");
int numberImageName = Integer.parseInt(intentImageName) +1;
EventBus.getDefault().post(new ImageNameEvent(""+numberImageName));;
}
This is the EventBus function used in the fragment to get the value from the BroadcastReceiver
@Subscribe
public void onEvent(ImageNameEvent event) {
imagename = Integer.parseInt(event.getMessage());
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("image", imagename);
editor.apply();
}
This is the onCreate function of the Fragment where the value of the shared preferences is retrieved.
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scheduleAlarm();
preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
int name = preferences.getInt("image", 0);
if (name != 0) {
imagename = name;
}
}
Any help would be appreciated.