如何在 sharedPreferences 中刷新/更新序列化 Java 对象 [英] How to refresh/Update Serialize Java Object in sharedPreferences

查看:73
本文介绍了如何在 sharedPreferences 中刷新/更新序列化 Java 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用于存储我使用以下代码的可串行化 java 对象

For storing the serilaizable java object i m using below code

if(sharedpreferences.getString(ComplexObjectXMl,"")!=null) {

                Serializer serializer = new Persister();
                MyObject example = null;
                try {
                    example = serializer.read(MyObject .class, sharedpreferences.getString(ComplexObjectXMl,""));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent i1 = new Intent(FirstActivity.this, SecondActivity.class);
                startActivity(i1);
            }
                new MyAsyncTask().execute();

在 MyAsyncTask 中,我将 XmlDataOverHttp 存储在 sharedPreferences 中.如果我喜欢这样做,它会每次都更新吗

In MyAsyncTask i m storing the XmlDataOverHttp in sharedPreferences. Will it get updated everytime if i like do this

推荐答案

你可以比较那些对象的字节数组.一个来自共享偏好,另一个是最新的.

you can compare byte array of those object. one coming from shared preference and other which is latest.

  byte[] array = new Gson().toJson(latestObject).getBytes(); //your lattest byte array
    byte[] secondArray = new Gson().toJson(objectConvertedFromSharedPreferenceOLD).getBytes();
    if (Arrays.equals(array, secondArray))

        System.out.println("They are same");
else
 System.out.println("Nope...");

正如您所说,您可以使用服务或共享首选项来检查 oncreateView() 中的每小时更新,但只有在用户打开您的应用时才会发生(在一个小时之间,它将为列表项调用 api)

and as you said you can use service or shared preference to check hourly update in oncreateView() but it only happens when user open your app(between hour it will call api for list items)

    SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences
                (Dashboard.this);
        long lastUpdateTime = mSettings.getLong("lastUpdateTime", 0);
        /* Should Activity Check for Updates Now? */
        if ((lastUpdateTime + (3600000)) < System.currentTimeMillis()) {

        /* Save current timestamp for next Check*/
            SharedPreferences.Editor editor = mSettings.edit();
            lastUpdateTime = System.currentTimeMillis();
            editor.putLong("lastUpdateTime", lastUpdateTime);
            editor.commit();

        /* Start Update for listview your URL to fetch data and then you can check and compare object 
also you can use swipeRefreshLayout so user can also refresh data*/
            //asyncRequestTime.execute(URL);
        } 

这篇关于如何在 sharedPreferences 中刷新/更新序列化 Java 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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