共享的偏好设置值不会第二次更新android [英] Shared preferences value not updating the second time android

查看:44
本文介绍了共享的偏好设置值不会第二次更新android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用广播接收器每24小时更改一次片段中变量的值.

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.

问题在于该值仅更改一次,并且不会再次更新.因此,如果值为10,它将变为11,但不会变为12.

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.

这是广播接收器

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));;

}

这是片段中用于从BroadcastReceiver获取值的EventBus函数

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();
}

这是Fragment的onCreate函数,在该函数中检索共享首选项的值.

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;
    }
}

任何帮助将不胜感激.

推荐答案

使用 editor.apply(),您正在执行异步操作,并且不返回任何内容. editor.commit()而是同步的,如果保存有效,则返回true,否则返回false.

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.

文档此处

因此,您可以尝试使用 commit()更改 apply(),并查看其返回true还是false.

So you can try to change apply() with commit() and see if it returns true or false.

这篇关于共享的偏好设置值不会第二次更新android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆