SharedPreferences读取旧值 [英] SharedPreferences reads old values

查看:69
本文介绍了SharedPreferences读取旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SharedPreferences在应用程序的不同活动中写入和读取以后的值.它过去可以正常工作,但是最近好像没有被刺激.我的意思是,我写了一个值,但是其他活动仍然读取旧值.有时它会正确地工作.有什么主意吗?

I use SharedPreferences to write and later read values within different activities in my application. It used to work ok but lately it seems like it if wasn't sincronized. I mean, I write a value but then the other activity still reads the old value. Sometimes it works correcly. Any idea?

这是一个示例代码:

首先,从线程开始:

SharedPreferences prefs = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("ComandToDo", value);
editor.commit();
... some code later:
alarmmanager.set(AlarmManager.RTC_WAKEUP, Miliseconds, sender);

在警报接收器中:

SharedPreferences prefs = contexto.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
int value = prefs.getInt("ComandToDo", -1);    

问题来了,因为值"不是线程中写入的值.

And here comes the problem because "value" is not the value written in the thread.

推荐答案

  1. SharedPreferences被记录为无法跨进程使用, http://developer.android.com/reference/android/content/SharedPreferences.html ,注意:当前此类不支持跨多个进程使用.稍后会添加."

  1. SharedPreferences are documented not to work across processes, http://developer.android.com/reference/android/content/SharedPreferences.html, "Note: currently this class does not support use across multiple processes. This will be added later."

此答案建议将数据封装到内容提供程序中,并且该讨论还考虑了其​​他一些选项,包括共享的SQLite:https://stackoverflow.com/a/5265556/1665128

This answer recommends encapsulation of data into a content provider, and the discussion also considers some other options, including shared SQLite: https://stackoverflow.com/a/5265556/1665128

您在文件系统中也有普通的旧文件.我们在几个项目中使用了它们,并进行了锁定,没有任何问题.也可能是您的选择.

You also have plain old files in the file system. We used them in several projects, with locking, without any issues. May be an option for you as well.

这篇关于SharedPreferences读取旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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