你如何在整个Android应用程序中持久化对象?

时间:2015-02-17 07:39:57

标签: java android

当应用程序加载时,我向Web服务发出请求,返回转换为Plain Old Java Objects的JSON:

机场:

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中存储会有点过分。

现在我已经阅读了有关使用Application Subclass,Singleton类和Shared Preferences的信息。

我不太确定哪种解决方案最适合这个问题?

2 个答案:

答案 0 :(得分:1)

选择您所说的方法之一取决于您对这些数据的行为。如果您希望在应用程序生命周期中保持这些数据的稳定性,那么使用单例或应用程序子类就可以了,但如果您希望这些数据在安装应用程序之前永久保持不变,则可能需要SQLite或文件或共享首选项。所以

在应用生命周期中持久

  • Java单例模式(通常使用静态成员)
  • Application
  • 的子类化

在安装应用之前保持不变

  • SQLite(通常用于大量数据)
  • 共享偏好(通常用于小数据)
  • 文件

请注意,SQLite和共享首选项方法比使用原始文件更有条理。

答案 1 :(得分:1)

如果json不是太大(kb中有几百个大小),请将json存储在共享首选项中。

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
}
相关问题