安卓:更新上的活动恢复共享prefereces不起作用 [英] Android: Updating SharedPrefereces on activity resume doesn't work

查看:167
本文介绍了安卓:更新上的活动恢复共享prefereces不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活性从<$​​ C $ C>共享preferences读取一些值,并在的TextView ,那么我所谓的b活动,其中的值共享preferences 得到更新和写回共享preferences 。最后,我回去活性,由pressing后退按钮,现在新(更新)值应从共享preferences读并显示在的TextView 。但这里说到的问题,共享preferences从刚读值仍然没有更新(不换新由b活动集)(来自logcat的输出得到了它),怎么弄的?请问共享preFS 需要某种手动刷新的?

I've got an "activity a" which reads some values from SharedPreferences and display them in a TextView, then I call "activity b" where the values from SharedPreferences get updated and written back to SharedPreferences. Finally I go back to "activity a" by pressing the back-button, now the new (updated) values should be read from SharedPreferences and shown in the TextView. But here comes the problem, the values just read from SharedPreferences are still not updated (are not the new ones set by activity b) (got it from logcat output), how comes that? Does SharedPrefs need some kind of manual refresh?

如果我重新启动活动是一切工作只是罚款和新值正常显示。发生什么事了?

If I restart "activity a" everything works just fine and the new values are shown properly. What's the matter?

我所说的方法来读取和显示来自 onResume值()中的活性。

I call the method to read and show the values from onResume() in "activity a".

我也试图重新实例共享preFS-对象(与 getShared preferences()),但它并没有帮助的。

I also tried to re-instantiate the SharedPrefs-Object (with getSharedPreferences()) but it doesn't help either.

在此先感谢!

推荐答案

您调用b活动的commit()方法来保存新的值。

Are you calling the commit() method in activity b to save the new values.

例如是这样的:

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

其次,你可以完成()的活性被发送到b活动之前,然后从活动的将被创建并的onCreate()将被称为活性巴新实例。

And secondly you can finish() the activity a before being sent to activity b, then from activity b a new instance of activity a will be created and onCreate() will be called.

另外,您可以刷新preferences在ONSTART(),因为你的行为可能是不可见时,发送到b活动。

Alternatively you can refresh the preferences in the onStart() because your activity is probably "no longer visible" when sent to activity b.

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

See http://developer.android.com/guide/topics/fundamentals/activities.html to see the activity lifecycle.

这篇关于安卓:更新上的活动恢复共享prefereces不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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