Android天气预报之基于HttpGet对象解析天气数据的方法_Android

本文实例所述为Android天气预报之解析天气数据的代码,可实现获取HttpGet对象读取天气网站天气数据,并从数据中解析出天气数据,比如温度、温度、风力、风向、未来几天天气趋势、当天天气状况、空气污染指数等信息,还包括了调用对应的图片或天气动画文件,对于开发android天气预报程序的可以参考本文实例。

具体功能代码如下:

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.lmw.weather.MyApp;
import org.lmw.weather.entity.WeatherEntity;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
/**
 * 解析天气数据
 * @author Dave
 */
public class WeatherData {
 private Activity activity;
 private FinalHttp fh;
 public static String def_weather_key="def_weather";
 public WeatherData(Activity activity) {
 this.activity = activity;
 fh = new FinalHttp();
 fh.configTimeout(1000 * 3);
 }
 public void getData(final String cityId,final Handler hd) {
 StringBuffer sb_url = new StringBuffer();
 sb_url.append("http://0.qnweather.duapp.com/weather.php?uri=");
 sb_url.append("http://m.weather.com.cn/data/");
 sb_url.append(cityId);
 sb_url.append(".html");
 final Message msg=new Message();
 fh.get(sb_url.toString(), new AjaxCallBack() {
  @Override
  public void onSuccess(Object t) {
  super.onSuccess(t);
  MySharedPreferences.writeMessage(activity, "def_weather",t.toString());
  msg.what=0;
  msg.obj=parseJson(t.toString());
  hd.sendMessage(msg);
  }
  @Override
  public void onFailure(Throwable t, int errorNo, String strMsg) {
  super.onFailure(t, errorNo, strMsg);
  System.out.println("-------errorNo---------"+errorNo);
  msg.what=-1;
  msg.arg1=errorNo;
  msg.obj=MySharedPreferences.readMessage(activity, def_weather_key, "");
  hd.sendMessage(msg);
  }
 });
 }
 private String connServerForResult(String strUrl) {
 // 获取HttpGet对象
 HttpGet httpRequest = new HttpGet(strUrl);
 String strResult = "";
 try {
  // HttpClient对象
  HttpClient httpClient = new DefaultHttpClient();
  // 获得HttpResponse对象
  HttpResponse httpResponse = httpClient.execute(httpRequest);
  if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
  // 取得返回的数据
  strResult = EntityUtils.toString(httpResponse.getEntity());
  }
 } catch (ClientProtocolException e) {
  e.printStackTrace();
 } catch (IOException e) {
  e.printStackTrace();
 } catch (Exception e) {
  e.printStackTrace();
 }
 System.out.println("rresult" + strResult);
 return strResult; // 返回结果
 }
 // 数据解析
 private WeatherEntity parseJson(String strResult) {
 WeatherEntity weather = null;
 try {
  JSONObject jsonObj = new JSONObject(strResult.replace("℃", "°"))
   .getJSONObject("weatherinfo");
  weather = new WeatherEntity();
  int ftime = jsonObj.getInt("fchh"); // 更新时间(整点)【更新时间确定temp属于哪天】
  int temp = 0; // 偏移
  if (ftime >= 18 || ftime < 8) {
  weather.setNight(true);
  temp = 1;
  }
  MyApp.week = jsonObj.getString("week");// 今天星期几
  weather.setCity(jsonObj.getString("city")); // 城市
  weather.setComfortable(jsonObj.getString("index")); // 舒适度
  weather.setRefreshDate(getDate()); // 更新日期
  weather.setRefreshTime(getTime()); // 更新时间
  weather.setRefreshWeek(getWeek()); // 更新星期
  weather.setPicIndex(jsonObj.getInt("img1")); // 当天天气图片编号
  List<Integer> topPic = new ArrayList<Integer>(); // 最高温时的图片编号
  if (temp == 1) {
  topPic.add(getSavePic(activity));
  } else {
  topPic.add(getJsonPic(jsonObj, "img", 1 + temp));
  savePic(activity, topPic.get(0));
  }
  topPic.add(getJsonPic(jsonObj, "img", 3 - temp));
  topPic.add(getJsonPic(jsonObj, "img", 5 - temp));
  topPic.add(getJsonPic(jsonObj, "img", 7 - temp));
  weather.setTopPic(topPic);
  List<Integer> lowPic = new ArrayList<Integer>(); // 最低温时的图片编号
  lowPic.add(getJsonPic(jsonObj, "img", 2 - temp));
  lowPic.add(getJsonPic(jsonObj, "img", 4 - temp));
  lowPic.add(getJsonPic(jsonObj, "img", 6 - temp));
  lowPic.add(getJsonPic(jsonObj, "img", 8 - temp));
  weather.setLowPic(lowPic);
  // ---------------------------以上为获取图片编号,暂且不管----------------------------------------------------------------------
  List<String> tempList = new ArrayList<String>(); // 未来五天温度(第一个是今天)
  tempList.add(jsonObj.getString("temp1"));
  tempList.add(jsonObj.getString("temp2"));
  tempList.add(jsonObj.getString("temp3"));
  tempList.add(jsonObj.getString("temp4"));
  tempList.add(jsonObj.getString("temp5"));
  tempList.add(jsonObj.getString("temp6"));
  MyApp.tempList.clear();
  MyApp.tempList = tempList;
  List<String> weatherList = new ArrayList<String>();// 未来五天天气(第一个是今天)
  weatherList.add(jsonObj.getString("weather1"));
  weatherList.add(jsonObj.getString("weather2"));
  weatherList.add(jsonObj.getString("weather3"));
  weatherList.add(jsonObj.getString("weather4"));
  weatherList.add(jsonObj.getString("weather5"));
  weatherList.add(jsonObj.getString("weather6"));
  MyApp.weatherList.clear();
  MyApp.weatherList = weatherList;
  List<String> tempListMax = new ArrayList<String>(); // 未来五天最高温度集合(有°符号)
  if (temp == 1) {
  tempListMax.add(getSaveTemperature(activity));
  } else {
  tempListMax
   .add(getTemperatureMaxAndMin(tempList.get(0))[0 + temp]);
  saveTemperature(activity, tempListMax.get(0));
  }
  tempListMax
   .add(getTemperatureMaxAndMin(tempList.get(1 - temp))[0 + temp]);
  tempListMax
   .add(getTemperatureMaxAndMin(tempList.get(2 - temp))[0 + temp]);
  tempListMax
   .add(getTemperatureMaxAndMin(tempList.get(3 - temp))[0 + temp]);
  weather.setTemperatureMax(tempListMax);
  weather.setTodayTemperature(getTemperatureMaxAndMin(tempList.get(0))[0]); // 当天温度(实时)
  weather.setTodayWeather(jsonObj.getString("img_title1")); // 当天天气描述(实时)
  List<String> tempListMin = new ArrayList<String>(); // 未来四天最低温度集合(有°符号)
  tempListMin.add(getTemperatureMaxAndMin(tempList.get(0))[1 - temp]);
  tempListMin.add(getTemperatureMaxAndMin(tempList.get(1))[1 - temp]);
  tempListMin.add(getTemperatureMaxAndMin(tempList.get(2))[1 - temp]);
  tempListMin.add(getTemperatureMaxAndMin(tempList.get(3))[1 - temp]);
  weather.setTemperatureMin(tempListMin);
  weather.setTomorrowTemperature(tempList.get(1)); // 明天温度(包括最高温和最低温)
  if (temp == 1) {
  weatherList.add(getSaveWeather(activity));
  } else {
  weatherList.add(jsonObj.getString("weather" + 1));
  saveWeather(activity, weatherList.get(0));
  }
  weatherList.add(jsonObj.getString("weather" + (2 - temp)));
  weatherList.add(jsonObj.getString("weather" + (3 - temp)));
  weatherList.add(jsonObj.getString("weather" + (4 - temp)));
  weather.setWeather(weatherList);
  weather.setTomorrowWeather(weatherList.get(1));
  List<String> windList = new ArrayList<String>(); // 未来四天风力
  windList.add(jsonObj.getString("wind1"));
  windList.add(jsonObj.getString("wind2"));
  windList.add(jsonObj.getString("wind3"));
  windList.add(jsonObj.getString("wind4"));
  weather.setWind(windList);
  weather.setMaxlist(transplate(tempListMax)); // 未来四天最高温度集合(无°符号)
  weather.setMinlist(transplate(tempListMin)); // 未来四天最低温度集合(无°符号)
 } catch (JSONException e) {
  e.printStackTrace();
 }
 return weather;
 }
 // 获取更新日期 并转换为(X月X日 周X)
 private String getDate() {
 SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 EEE", Locale.CHINA);
 String date = sdf.format(new java.util.Date());
 System.out.println(date);
 return date;
 }
 // 获取更新时间 并转换为 (小时:分钟 更新)
 private String getTime() {
 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
 String time = sdf.format(new java.util.Date()) + " " + "更新";
 System.out.println(time);
 return time;
 }
 private String getWeek() {
 return null;
 }
 // 获取最高温度和最低温度,有°符号
 private String[] getTemperatureMaxAndMin(String str) {
 return str.split("~");
 }
 // 去除最高温度和最低温度里的°符号
 private List<Integer> transplate(List<String> strList) {
 List<Integer> intList = new ArrayList<Integer>();
 for (String temp : strList) {
  intList.add(Integer.valueOf(temp.split("°")[0]));
 }
 return intList;
 }
 // 获取图片编号 例如"img" + "1"
 private int getJsonPic(JSONObject jsonObj, String str, int index)
  throws JSONException {
 int result = jsonObj.getInt(str + index);
 if (result == 99 && index > 1) {
  index--;
  result = jsonObj.getInt(str + index);
 }
 return result;
 }
 private void saveTemperature(Activity activity, String value) {
 // MySharedPreferences mp = new MySharedPreferences(activity);
 // mp.writeMessage("temperature", value);
 }
 // 保存的温度
 private String getSaveTemperature(Activity activity) {
 return MySharedPreferences.readMessage(activity,"temperature", "100");
 }
 private void saveWeather(Activity activity, String value) {
 // MySharedPreferences mp = new MySharedPreferences(activity);
 // mp.writeMessage("weather", value);
 }
 // 保存的天气
 private String getSaveWeather(Activity activity) {
 return MySharedPreferences.readMessage(activity,"weather", "");
 }
 private void savePic(Activity activity, int value) {
 // MySharedPreferences mp = new MySharedPreferences(activity);
 // mp.writeMessage("pic", value);
 }
 // 保存的天气图片编号
 private int getSavePic(Activity activity) {
 return MySharedPreferences.readMessage(activity,"pic", 99);
 }
}

希望本文实例对大家Android天气预报程序的开发能够起到一定的帮助作用。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索android
, 天气预报
, httpget
对象解析
天气预报json解析、天气预报xml解析、json解析嵌套天气预报、json解析获取天气预报、天气预报,以便于您获取更多的相关知识。

时间: 2024-08-31 05:54:50

Android天气预报之基于HttpGet对象解析天气数据的方法_Android的相关文章

Android天气预报之基于HttpGet对象解析天气数据的方法

本文实例所述为Android天气预报之解析天气数据的代码,可实现获取HttpGet对象读取天气网站天气数据,并从数据中解析出天气数据,比如温度.温度.风力.风向.未来几天天气趋势.当天天气状况.空气污染指数等信息,还包括了调用对应的图片或天气动画文件,对于开发android天气预报程序的可以参考本文实例. 具体功能代码如下: import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayL

Android编程实现基于BitMap获得图片像素数据的方法_Android

本文实例讲述了Android编程实现基于BitMap获得图片像素数据的方法.分享给大家供大家参考,具体如下: 网上看到的参考是: int[] pixels = new int[bit.getWidth()*bit.getHeight()];//保存所有的像素的数组,图片宽×高 bit.getPixels(pixels,0,bit.getWidth(),0,0,bit.getWidth(),bit.getHeight()); for(int i = 0; i < pixels.length; i+

Android编程实现基于BitMap获得图片像素数据的方法

本文实例讲述了Android编程实现基于BitMap获得图片像素数据的方法.分享给大家供大家参考,具体如下: 网上看到的参考是: int[] pixels = new int[bit.getWidth()*bit.getHeight()];//保存所有的像素的数组,图片宽×高 bit.getPixels(pixels,0,bit.getWidth(),0,0,bit.getWidth(),bit.getHeight()); for(int i = 0; i < pixels.length; i+

Android解析JSON数据的方法分析_Android

本文实例讲述了Android解析JSON数据的方法.分享给大家供大家参考,具体如下: JSON作为一种"轻量"的数据结构传递数据,在JS中有广泛的应用 Google公司对JSON的解析提供了gson.jar这个包,它不依赖于其他任何JAR包:自从Android3.0中已经合入了该解析器的功能,但之前的版本是没有的. findViewById(R.id.parseBtn).setOnClickListener(new OnClickListener(){ @Override public

Android解析JSON数据的方法分析

本文实例讲述了Android解析JSON数据的方法.分享给大家供大家参考,具体如下: JSON作为一种"轻量"的数据结构传递数据,在JS中有广泛的应用 Google公司对JSON的解析提供了gson.jar这个包,它不依赖于其他任何JAR包:自从Android3.0中已经合入了该解析器的功能,但之前的版本是没有的. findViewById(R.id.parseBtn).setOnClickListener(new OnClickListener(){ @Override public

Android编程使用sax解析xml数据的方法详解

本文实例讲述了Android编程使用sax解析xml数据的方法.分享给大家供大家参考,具体如下: 随着技术的发展,现在的web已经和以前不同了.web已经逐渐像移动的方向倾斜,作为程序员的确应该拓展一下自己的知识层面.学习各方面的知识,今天就接着前几天的弄一下Android的xml解析,这次就使用sax的方式解析xml.下面就一步一步的来做吧. 1. 编写一个简单的xml <?xml version="1.0" encoding="UTF-8"?> &l

SQL Server解析XML数据的方法详解_MsSql

本文实例讲述了SQL Server解析XML数据的方法.分享给大家供大家参考,具体如下: --5.读取XML --下面为多种方法从XML中读取EMAIL DECLARE @x XML SELECT @x = ' <People> <dongsheng> <Info Name="Email">dongsheng@xxyy.com</Info> <Info Name="Phone">678945546</

SQL Server解析XML数据的方法详解

本文实例讲述了SQL Server解析XML数据的方法.分享给大家供大家参考,具体如下: --5.读取XML --下面为多种方法从XML中读取EMAIL DECLARE @x XML SELECT @x = ' <People> <dongsheng> <Info Name="Email">dongsheng@xxyy.com</Info> <Info Name="Phone">678945546</

Android编程实现获取新浪天气预报数据的方法_Android

本文实例讲述了Android编程实现获取新浪天气预报数据的方法.分享给大家供大家参考,具体如下: 新浪天气预报地址: http://php.weather.sina.com.cn/xml.php?city=武汉&password=DJOYnieT8234jlsK&day=0 其中,city后的城市可用java.net.URLEncoder.encode("武汉"," gb2312");也可以直接写"武汉",但不能用"wu