简体   繁体   English

共享的偏好设置值不会第二次更新android

[英]Shared preferences value not updating the second time android

I have used a Broadcast receiver to change the value of a variable inside my fragment every 24 hours. 我已经使用广播接收器每24小时更改片段中变量的值。

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. 因此,如果值为10,它将更改为11,但不会变为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 这是片段中用于从BroadcastReceiver获取值的EventBus函数

  @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. 这是Fragment的onCreate函数,在该函数中检索共享首选项的值。

    @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. 任何帮助,将不胜感激。

Using editor.apply() you are doing asynchronous, and doesn't return nothing. 使用editor.apply()您正在执行异步操作,并且不返回任何内容。 editor.commit() instead is synchronous and returns true if the save works, false otherwise. editor.commit()相反是同步的,如果保存有效,则返回true,否则返回false。

Docs here 文件在这里

So you can try to change apply() with commit() and see if it returns true or false. 因此,您可以尝试使用commit()更改apply() ,看看它是否返回true或false。

而不是editor.apply()可以使用editor.commit()不确定原因,但是对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM