使用 SharedPreferences 进行 Android 初始化
我对 SharedPrefences 和初始化有疑问。
我的应用程序有一个登录名,您可以在其中插入用户,并且对于该用户,您有特定的首选项...因此,我需要根据用户保存首选项以便稍后加载。
我认为 SharedPrefences 是解决方案,而且我确实这么认为,但我在初始化它们时遇到了问题:我有一个名为 Options 的 Activity 类。它有返回选项值的静态函数...但我有一个问题,我在创建该活动(意图)之前调用该函数,所以我认为这些函数返回最后一个用户的最后一个值在选项上选择...
如何在调用之前加载选项?
我想首先使用 Intent 向用户发送额外的数据,并在选项的 onCreate() 中初始化它们,但如果我做出意图,那么选项将出现(xml 将加载)。
有什么帮助吗?
I have a problem with SharedPrefences and initializations.
My application has a login where you insert an user, and for that user, you have a specific preferences... so, I need to save preferences according to the user to load it later.
I though that SharedPrefences would be the solution, and it really is I think, but I have a problem to initialize they: I have an Activity class called Options. It has static functions that returns the value of the options... but I have a problem, I call that functions before I have create that activity (intent), so I think that the functions are returning the last value that the last user has selected on the options...
How can I load the options before that calls?
I though to use first of all an Intent sending extra data with the user and in onCreate() of the Options, initialize they, but if I make an intent, then the Options will appear (xml will load).
Any help pls?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这样的事情......为每个要保存的变量添加方法。
Try something like this.... adding methods for each variable you want to save.
所有
SharedPreferences
需要的只是一个context
并且它可以被初始化。由于您的应用程序总是首先打开一个Activity
,因此您始终有一个上下文
可以使用。我建议您将
SharedPreferences
包装在Singleton
类中,并在getInstance
处将context
作为参数传递方法。您应该能够通过这种方式访问您在所有活动中的共享偏好设置。All the
SharedPreferences
need is acontext
and it can be initialized. As your application always opens anActivity
to start with, you always have acontext
to work with.I would advise you to wrap the
SharedPreferences
in aSingleton
class and just pass acontext
as parameter at thegetInstance
method. You should be able to access your shared preferences at all Activities this way.我致力于 Android 的依赖注入器,并且共享首选项的内容已经可以注入到带注释的字段中(请参阅: https:// github.com/ko5tik/andject,PreferenceInjector)。欢迎补丁和改进。即将保存首选项
I work on the dependency injector for android, and content of shared preferences is already injectable into annotated fields ( see: https://github.com/ko5tik/andject , PreferenceInjector). Patches and improvements are welcome. Saving of preferences comes soon