将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();
}