调用网络服务,您可以将每个国家/地区作为 JSON 字符串存储到数据库中,其中包含整个城市列表,例如:
{"id": "1", "name": "coutry1", "cities": [{"id": "1", "name": "city1"},{"id": "2", "name": "city2"},{"id": "3", "name": "cityx"}]}
稍后在 SQLite 上提出您的请求,您可以使用此 JSONObject 创建 Country 实例
public class Country extends BaseElement{
private ArrayList<City> cities;
// Imagine that for each country we are storing the kind of JSON into the DB
// {"id": "1", "name": "coutry1", "cities": [{"id": "1", "name": "city1"},{"id": "2", "name": "city2"},{"id": "3", "name": "cityx"}]}
public Country(String jsonFromDB){
cities = new ArrayList<City>();
if(jsonFromDB != null && jsonFromDB.trim().length() > 0){
try {
JSONObject country = new JSONObject(jsonFromDB);
setId(country.getInt("id"));
setName(country.getString("name"));
JSONArray cts = country.getJSONArray("cities");
for(int i = 0; i < cts.length() ; i++){
cities.add(new City(cts.getJSONObject(i)));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public ArrayList<City> getCities(){
return cities;
}
}
public class City extends BaseElement{
public City(JSONObject jsonFromDB) throws JSONException{
if(jsonFromDB != null){
setId(jsonFromDB.getInt("id"));
setName(jsonFromDB.getString("name"));
}
}
}
public class BaseElement{
private int id;
private String name;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
}
然后,您可以在任何类型的适配器中使用 Country 的实例,用于微调器、列表或可扩展列表......