2016-05-15 74 views
0

为了存储serilaizable Java对象/更新序列化Java对象I M使用以下代码如何刷新在sharedPreferences

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 I M存储在sharedPreferences的XmlDataOverHttp。它会每次更新如果我喜欢这样做

回答

1

你可以比较这些对象的字节数组。一个来自共享偏好和其他最新的。

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)

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

它的对象具有关于应用程序的所有信息。我不想每次都从服务器获取该对象,只想在服务器上更改时才加载。这就是为什么把它存储在共享首选项 –

+0

如果我能够刷新这个对象每小时,这将有助于很多,但不是每次。根据我需要每次比较对象的方法 –

+0

它对你有帮助吗?或者您想使用小时内运行的服务来检查更新的数据。 –