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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值