HOWTO读取更新后的共享preferences? [英] Howto read updated shared preferences?

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

问题描述

我有两个活动:一个(SettingsActivity),从而节省了preferences中的onStop()是这样的:

 共享preferences.Editor编辑= getShared preferences(我的preFS,Context.MODE_PRIVATE).edit();editor.putString(登录,etLogin.getText()的toString());
editor.putString(密码,etPassword.getText()的toString());editor.commit();

和第二个(MainActitivy),它像

读取它们在onResume()

 共享preferences preFS = activity.getShared preferences(我的preFS,Context.MODE_PRIVATE);
prefs.getString(...);

当我更改设置并返回到主活动,旧值装!我要再次打开SettingsActivity又一次回去,变化发生。

时的onStop()在单独的线程中运行旁边onResume储蓄例程(),因此读取数据时,变更尚未COMMITED?如何实现正确行为?

肮脏的解决方案的想法:我在想一个单身,这对我的preferences并有保存()和load(),但是这是丑陋的解决方案,我想知道,如何正确地做到这一点<。 / p>

解决方案

做了SettingsActivity已采空,如果没有,你必须调用finish();保存用户名和密码后调用的onStop()方法(活动周期)。

如果你只是打电话给你的保存方法和hiting背面按钮的onStop()方法,将不会触发回的主要活动。由于SettingsActivity仍在运行,并在背景中暂停。

I have two Activities: one (SettingsActivity), which saves preferences in onStop() like this:

SharedPreferences.Editor editor = getSharedPreferences("myprefs", Context.MODE_PRIVATE).edit();

editor.putString("login", etLogin.getText().toString());
editor.putString("password", etPassword.getText().toString());

editor.commit();

and second one (MainActitivy), which reads them in onResume() like

SharedPreferences prefs = activity.getSharedPreferences("myprefs", Context.MODE_PRIVATE);
prefs.getString(...);

When I change settings and return back to main activity, old values are loaded! I have to open SettingsActivity again and go back again, to changes take place.

Is onStop() with saving routines running in separate thread next to onResume() so when reading, changes are not commited yet? How to achieve correct behavior?

Dirty solution idea: I'm thinking about a singleton, which holds my preferences and has save() and load(), but this is ugly solution and I want to know, how to do this properly.

解决方案

Did the SettingsActivity has stoped if no you have to call finish(); to call the onstop() method (activity lifecycle) after saving username and password.

If you just call your save method and go back to the main activity by hiting the back button the onStop() method is not fired. Because the SettingsActivity is still running and paused in background.

这篇关于HOWTO读取更新后的共享preferences?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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