【问题标题】:Using singleton with shared preferences?使用具有共享偏好的单例?
【发布时间】:2014-08-13 10:48:56
【问题描述】:

我正在使用单例在我的应用程序中存储全局数据。 这部分数据已在线下载,其他已保存在偏好设置中。

 public class MySingleton {
        private static MySingleton mInstance;

        private MySingleton() {

        }

        public static synchronized MySingleton getInstance() {
            if (mInstance == null) {
                mInstance = new MySingleton();
            }
            return mInstance;

        }
    private City city; // I download the city online
    private int userId; // I save the userId in the preferences

    public City getCity(){
    return city;
    }
    public void setCity(City city){
    this.city = city;
    }

    public int getUserId(){
    return userId;
    }

    public void setUserId(int userId){
    this.userId = userId;
    }

我在第一个活动中在线下载了cityObject,然后将它们设置在单例对象上;

我的问题是当应用程序在后台时,操作系统会杀死应用程序和对象城市,然后单例变为空;

我的解决方案是将城市对象保存在首选项中,当我下载第一个活动时,当城市为空时,我从首选项而不是互联网获取它。

这样做是否明智?

【问题讨论】:

    标签: android singleton sharedpreferences


    【解决方案1】:

    您可以将您的城市对象“转换”为 JSON,并将其作为字符串保存在您的 sharedPreferences 中。回来后,您可以读取 JSON 字符串并将其转换回 City 对象。

    您可以使用Gson Library 轻松实现这一目标。请参阅以下示例:

    https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples

    【讨论】:

    • 这是个好主意,谢谢,实际上每次单例变为空时,我都会从首选项重新启动它。然后我将使用单例而不是首选项,我这样做是因为我认为这样更快,对吗?
    • 最好有一个类来“协调”从互联网收集数据并将其存储在首选项中的工作......所以这个类的“用户”不知道这些细节。如果你想把它封装在这个单例中也没关系。
    猜你喜欢
    • 2017-09-27
    • 2016-04-19
    • 1970-01-01
    • 2021-04-01
    • 2014-12-31
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    相关资源
    最近更新 更多