1. 程式人生 > >JSON格式的天氣資訊解析並儲到本地SharedPreferences

JSON格式的天氣資訊解析並儲到本地SharedPreferences

將JSON格式的天氣資訊進行解析,並儲到本地SharedPreferences,以下為簡單原始碼:

/**
     * 解析伺服器返回的JSON資料,並將解析出的資料儲存到本地。
     * @param context
     * @param response  網路返回資料字串
     */
    public static void handleWeatherResponse(Context context, String response){
        try {
            JSONObject jsonObject=new JSONObject(response);
            JSONObject weatherInfo=jsonObject.getJSONObject("result"
); String date=weatherInfo.getString("days"); //當前日期 String week=weatherInfo.getString("week"); //星期 String cityName=weatherInfo.getString("citynm"); //城市名 String temperature_curr=weatherInfo.getString("temperature_curr"); //當前溫度 String humidity=weatherInfo.getString("humidity"
); //溼度 String weather=weatherInfo.getString("weather"); //天氣情況 String wind=weatherInfo.getString("wind"); //風向 String winp=weatherInfo.getString("winp"); //風級 String temp_high = weatherInfo.getString("temp_high"); String temp_low = weatherInfo.getString("temp_low"
); saveWeatherInfo(context, date, week,cityName,temperature_curr, humidity, weather, wind,winp,temp_high,temp_low); } catch (JSONException e) { e.printStackTrace(); } } /** * 將伺服器返回的所有天氣資訊儲存到SharedPreferences。 * @param context * @param date 日期 * @param week 星期 * @param cityName 城市名 * @param temperature_curr 當前溫度 * @param humidity 溼度 * @param weather 天氣情況 * @param wind 風向 * @param winp 風力 * @param temp_high 最高溫度 * @param temp_low 最低溫度 */ private static void saveWeatherInfo(Context context, String date, String week, String cityName, String temperature_curr, String humidity, String weather, String wind, String winp, String temp_high, String temp_low) { SharedPreferences.Editor editor= PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putBoolean("city_selected", true); editor.putString("days",date); editor.putString("week",week); editor.putString("city_name", cityName); editor.putString("temperature_curr", temperature_curr); editor.putString("humidity", humidity); editor.putString("weather", weather); editor.putString("wind", wind); editor.putString("winp", winp); editor.putString("temp_high", temp_high); editor.putString("temp_low", temp_low); editor.commit(); }