天氣開發2——第二行代碼(酷歐天氣)

上一篇我們對本項目需要使用到的開源庫做了簡單使用介紹,接下來進入正軌。

網絡傳輸

我們在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();
發佈了43 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章