2

我有一个“活动 a”,它从中读取一些值SharedPreferences并将它们显示在 a 中TextView,然后我调用“活动 b”,其中的值SharedPreferences被更新并写回SharedPreferences. 最后,我通过按后退按钮返回“活动 a”,现在应该SharedPreferencesTextView. 但是问题来了,刚刚读取的值SharedPreferences仍然没有更新(不是活动b设置的新值)(从logcat输出中得到),这是怎么回事?是否SharedPrefs需要某种手动刷新?

如果我重新启动“活动 a”,一切都会正常工作,并且新值会正确显示。怎么了?

我调用该方法来读取和显示onResume()“活动 a”中的值。

我还尝试重新实例化 SharedPrefs-Object (使用getSharedPreferences()),但它也无济于事。

提前致谢!

4

5 回答 5

2

您是否在活动 b 中调用 commit() 方法来保存新值。

例如:

SharedPreferences customSharedPreference = getSharedPreferences("abcprefs", 0);
SharedPreferences.Editor editor = customSharedPreference.edit();
editor.putString("key", "val");
editor.commit();

其次,您可以在发送到活动 b 之前完成()活动 a,然后从活动 ba 中创建活动 a 的新实例并调用 onCreate()。

或者,您可以刷新 onStart() 中的首选项,因为您的活动在发送到活动 b 时可能“不再可见”。

请参阅http://developer.android.com/guide/topics/fundamentals/activities.html以查看活动生命周期。

于 2011-06-09T13:40:32.223 回答
1

SharedPreferences不适用于在活动之间共享数据

使用IntentActivity.startActivityForResult。在此处查看我的答案 获取活动中的意图对象

于 2011-06-09T13:34:39.510 回答
0

确保您在每个活动中使用相同的首选项:如果您使用getSharedPreferences,则应指定文件和访问级别。在你的情况下,这听起来像是getDefaultSharedPreferences要走的路。

此外,请确保您不仅要设置首选项,还要提交更改:

SharedPreferences preferences = getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("key", "value");
editor.commit();

然后在您的其他活动中:

SharedPreferences preferences = getDefaultSharedPreferences(this);
boolean myPreference = preferences.getBoolean("key", defaultValue);

如果您发布有问题的代码,这将更容易提供帮助;如果您仍然无法使其正常工作,我会尝试将其添加到您的帖子中。

于 2011-06-09T14:27:51.837 回答
0

还值得注意的是,preference.edit()SharedPreferences.Editor每次调用它都会返回一个不同的值,因此将编辑器存储到一个单独的变量中,使用它来写出首选项然后提交该编辑器是很重要的。例如,这将不起作用:

myPrefs.edit().putInt("pref", 1);
myPrefs.edit().putBoolean("pref", true);
myPrefs.edit().commit();

它需要(如已证明的那样):

SharedPreferences myPrefs = getSharedPreferences("pref_name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putInt("pref", 1);
editor.putBoolean("pref", true);
editor.commit();
于 2012-01-07T19:36:31.077 回答
0

为了能够使用从活动 B 发送到 SharedPreferences 的数据更新您的活动 A,同时从 B 恢复活动 A,请执行以下操作:

  1. 在您的应用清单中,将活动 A“launchMode”设置为“标准”

  2. 从活动 B 完成并返回活动 A 后,将“FLAG_ACTIVITY_CLEAR_TOP”的意图标志添加到您的意图中,如下所示:

    Intent intent = new Intent(activityB.this, activityA.class); 意图.addFlags(意图.FLAG_ACTIVITY_CLEAR_TOP);开始活动(意图);结束();

解释代码: “FLAG_ACTIVITY_CLEAR_TOP”检查正在启动的活动 A 是否已经在当前任务中运行,然后不是启动该活动的新实例,而是销毁它之上的所有其他活动,并将此意图传递给Activity 的恢复实例(现在在顶部),通过 onNewIntent 方法。点击此链接了解更多关于 android 任务和回栈的信息:https ://blog.mindorks.com/android-task-and-back-stack-review-5017f2c18196

希望这可以帮助...

于 2019-09-18T11:47:46.173 回答