上一篇我们对本项目需要使用到的开源库做了简单使用介绍,接下来进入正轨。
网络传输
我们在util中创建HttpUtil来进行网络的传输
public class HttpUtil {
public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(address).build();
client.newCall(request).enqueue(callback);//回调方法
}
}
使用litepal创建并操作数据库
上一篇我们已经在使用litepal的介绍中,把数据库创建好了。我们是在db包下面创建了Province,City,County三个类,也就是三个表,接下来就是如何操作数据库。
我们在util包中创建一个工具类Utility,
主要任务是:向服务器发送请求,将接受到的Json数据进行解析后存储到相应的数据库中,代码比较长,要耐心看:
//解析服务器的数据并存储到数据库中
public class Utility {
//json={"id":1,"name":"北京"}
public static boolean handleProvinceResponse(String response) {
//判断服务器返回的数据是否为空
if (!TextUtils.isEmpty(response)){
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
//创建记录
Province province = new Province();
JSONObject object = jsonArray.getJSONObject(i);
province.setProvinceCode(object.getInt("id"));
province.setProvinceName(object.getString("name"));
province.save();//存储到数据库
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
//城市
public static boolean handleCityResponse(String response, int provinceId) {
if (!TextUtils.isEmpty(response)) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0;i<jsonArray.length();i++) {
City city = new City();
JSONObject object = jsonArray.getJSONObject(i);
city.setProvinceId(provinceId);
city.setCityCode(object.getInt("id"));
city.setCityName(object.getString("name"));
city.save();
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
//县 json={"id":937,"name":"苏州","weather_id":"CN10110401"}
public static boolean handleCountyResponse(String response, int cityId) {
if (!TextUtils.isEmpty(response)) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i=0;i<jsonArray.length();i++) {
County county = new County();
JSONObject object = jsonArray.getJSONObject(i);
county.setCityId(cityId);
county.setCountyName(object.getString("name"));
county.setWeatherId(object.getString("weather_id"));
county.save();
}
return true;
} catch (JSONException e) {
e.printStackTrace();
}
}
return false;
}
由于天气的返回数据如下:
注意这是和风天气x3版本的内容,同时要去和风天气注册信息,获得key,下图在控制台中查看
{
"HeWeather data service 3.0": [{
"status": "ok", //接口状态
"basic":{},
"aqi":{},
"now":{},
"suggestion":{},
"daily-forecast":{}
}]
}
weather的信息比较复杂,所以我们使用的是gson
Basic,Aqi,Now,Suggestion,Forecast,Weather类分别对应Json数据。
"basic": { //基本信息
"city": "北京", //城市名称
"id": "CN101010100", //城市ID
"update": { //更新时间
"loc": "2015-07-02 14:44", //当地时间
}
public class Basic {
@SerializedName("city")
public String cityName;
@SerializedName("id")
public String weatherId;
public Update update;
public class Update{
@SerializedName("loc")
public String updateTime;
}
}
"now": { //实况天气
"cond": { //天气状况
"txt": "晴" //天气状况描述
},
"tmp": "32", //温度
}
public class Now {
@SerializedName("tmp")
public String tmp;
public Cond cond;
public class Cond {
@SerializedName("txt")
public String txt;
}
}
"aqi": { //空气质量,仅限国内城市
"city": {
"aqi": "30", //空气质量指数
"pm25": "7", //PM2.5 1小时平均值(ug/m³)
}
public class Aqi {
public AqiCity city;
public class AqiCity{
@SerializedName("aqi")
public String aqi;
@SerializedName("pm25")
public String pm;
}
}
"suggestion": { //生活指数,仅限国内城市
"comf": { //舒适度指数
"txt": "白天天气多云,同时会感到有些热,不很舒适。" //详细描述
},
"cw": { //洗车指数
"txt": "较适宜洗车,未来一天无雨,风力较小,擦洗一新的汽车至少能保持一天。"
},
"sport": { //运动指数
"txt": "天气较好,户外运动请注意防晒。推荐您进行室内运动。"
}
}
public class Suggestion {
public Comf comf;
public Cw cw;
public Sport sport;
public class Comf{
public String txt;
}
public class Cw{
public String txt;
}
public class Sport{
public String txt;
}
}
"daily_forecast": [ //天气预报,国内7天,国际10天
{
"date": "2015-07-02", //预报日期
"cond": { //天气状况
"txt_d": "晴", //白天天气状况描述
},
"tmp": { //温度
"max": "34", //最高温度
"min": "18" //最低温度
}
},
...... //略
}
//是daily_forecast的一个部分内容
public class Forecast {
public String date;
public Cond cond;
public Tmp tmp;
public class Cond{
@SerializedName("txt_d")
public String txt;
}
public class Tmp{
public String max;
public String min;
}
}
//总的Weather类,用来管理"HeWeather data service 3.0'
public class Weather {
public String status;
public Basic basic;
public Aqi aqi;
public Now now;
public Suggestion suggestion;
@SerializedName("daily_forecast")
public List<Forecast> forecastList;
}
我们在来看看json数据格式,
{
"HeWeather data service 3.0": [{
"status": "ok", //接口状态
"basic":{},
"aqi":{},
"now":{},
"suggestion":{},
"daily-forecast":{}
}]
}
//将返回的Json数据解析成Weather实体
public static Weather handleWeatherResponse(String response) {
try {
//将其拆分成{"HeWeather data service 3.0": [{}]}看待
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("HeWeather data service 3.0");
String weatherContent = jsonArray.getJSONObject(0).toString();
return new Gson().fromJson(weatherContent,Weather.class);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
拆分成{“HeWeather data service 3.0”: [{}]}看待,weatherContent就等价于下面的内容,也就是数组中第0个元素值。
String weatherContent = jsonArray.getJSONObject(0).toString();