[英]How do you persist an object throughout an android application?
當應用程序加載時,我對返回JSON的Web服務發出請求,該JSON被轉換為Plain Old Java Objects:
機場:
public class Airports {
private List<Airport> airportList = new ArrayList<Airport>();
...get and set...
}
飛機場:
public class Airport {
private String id;
private String airport;
private String city;
...get and set...
}
現在,因為每次都執行請求很昂貴,所以我希望可以在整個應用程序中訪問此機場列表(機場對象)。 如何訪問該對象的單個實例的數據。
在SQLite中存儲將是過大的。
現在,我已閱讀有關使用應用程序子類,單例類和共享首選項的信息。
我不太確定哪種解決方案最適合該問題?
選擇您所說的方式之一是基於您希望這些數據采取何種行為。 如果您希望這些數據在應用程序生命周期中保持穩定,則可以使用singleton或應用程序子類,但否則,如果您希望這些數據在安裝應用程序之前一直保持不變,則可能需要SQLite或文件或“共享首選項”。 所以
在應用程序生命周期中持續存在
Application
類的子類 持續到安裝應用程序
請注意,與使用原始文件相比,SQLite和共享首選項方法的結構更為合理。
如果json不太大(將幾百個大小以kb為單位)存儲在共享首選項中。
SharedPreferences.Editor editor = preferences.edit();
editor.putString("jsondata", jsonData.toString());
editor.commit();
恢復:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String stringJson = sharedPref.getString("jsondata");
if(stringJson != null){
JSONObject jsonData = new JSONObject(stringJson);
}else{
//retrieve from web services
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.