How to refresh/Update Serialize Java Object in sharedPreferences

流过昼夜 提交于 2019-12-25 07:41:30

问题


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();

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


回答1:


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...");

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);
        } 


来源:https://stackoverflow.com/questions/37243996/how-to-refresh-update-serialize-java-object-in-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!