问题
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.
回答1:
Using editor.apply()
you are doing asynchronous, and doesn't return nothing. editor.commit()
instead is synchronous and returns true if the save works, false otherwise.
Docs here
So you can try to change apply()
with commit()
and see if it returns true or false.
回答2:
Instead of editor.apply() use editor.commit() Not really sure of the reason but it worked for me.
来源:https://stackoverflow.com/questions/42066715/shared-preferences-value-not-updating-the-second-time-android