天气预报XML-Pull解析版(完全解析)

事先声明,我用的是4.2的工程版本,使用真机HTC G14测试的4.0系统,没有问题。

1.首先根据google提供的接口http://www.google.com/ig/api?weather=beijing查看这个文件,如下

<xml_api_reply version="1">
	<weather module_id="0" tab_id="0" mobile_row="0" mobile_zipped="1" row="0" section="0">
		<forecast_information>
			<city data="Beijing, Beijing"/>
			<postal_code data="beijing"/>
			<latitude_e6 data=""/>
			<longitude_e6 data=""/>
			<forecast_date data="2012-07-31"/>
			<current_date_time data="2012-08-01 05:30:00 +0000"/>
			<unit_system data="SI"/>
		</forecast_information>
		<current_conditions>
			<condition data="小雨"/>
			<temp_f data="68"/>
			<temp_c data="20"/>
			<humidity data="湿度: 100%"/>
			<icon data="/ig/images/weather/cn_lightrain.gif"/>
			<wind_condition data="风向: 北、风速:4 米/秒"/>
		</current_conditions>
		<forecast_conditions>
			<day_of_week data="周二"/>
			<low data="20"/>
			<high data="24"/>
			<icon data="/ig/images/weather/cn_heavyrain.gif"/>
			<condition data="雨"/>
		</forecast_conditions>
		<forecast_conditions>
			<day_of_week data="周三"/>
			<low data="19"/>
			<high data="27"/>
			<icon data="/ig/images/weather/chance_of_rain.gif"/>
			<condition data="可能有雨"/>
		</forecast_conditions>
		<forecast_conditions>
			<day_of_week data="周四"/>
			<low data="21"/>
			<high data="28"/>
			<icon data="/ig/images/weather/mostly_sunny.gif"/>
			<condition data="晴间多云"/>
		</forecast_conditions>
		<forecast_conditions>
			<day_of_week data="周五"/>
			<low data="22"/>
			<high data="28"/>
			<icon data="/ig/images/weather/cn_fog.gif"/>
			<condition data="雾"/>
		</forecast_conditions>
	</weather>
</xml_api_reply>

2.根据这个接口,写几个工具类,非常简单,如下代码

就按照所给接口的节点名字写类名

第一个类如下,作用看类名,预测情况

package mars.com;

public class WeatherForecastCondition {
	private String day_of_week = null;
	private String low = null;
	private String high = null;
	private String iconURL = null;
	private String condition = null;

	public String getDay_of_week() {
		return day_of_week;
	}

	public void setDay_of_week(String day_of_week) {
		this.day_of_week = day_of_week;
	}

	public String getLow() {
		return low;
	}

	public void setLow(String low) {
		this.low = low;
	}

	public String getHigh() {
		return high;
	}

	public void setHigh(String high) {
		this.high = high;
	}

	public String getIconURL() {
		return iconURL;
	}

	public void setIconURL(String iconURL) {
		this.iconURL = iconURL;
	}

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

}
第二个类如下,当前天气情况

package mars.com;

public class WeatherCurrentCondition {
	private String condition = null;
	private String temp_f = null;
	private String temp_c = null;
	private String humidity = null;
	private String iconURL = null;
	private String wind_condition = null;

	public String getCondition() {
		return condition;
	}

	public void setCondition(String condition) {
		this.condition = condition;
	}

	public String getTemp_f() {
		return temp_f;
	}

	public void setTemp_f(String temp_f) {
		this.temp_f = temp_f;
	}

	public String getTemp_c() {
		return temp_c;
	}

	public void setTemp_c(String temp_c) {
		this.temp_c = temp_c;
	}

	public String getHumidity() {
		return humidity;
	}

	public void setHumidity(String humidity) {
		this.humidity = humidity;
	}

	public String getIconURL() {
		return iconURL;
	}

	public void setIconURL(String iconURL) {
		this.iconURL = iconURL;
	}

	public String getWind_condition() {
		return wind_condition;
	}

	public void setWind_condition(String wind_condition) {
		this.wind_condition = wind_condition;
	}

}
第三个类如下,天气预测信息

package mars.com;

public class WeatherForecastInformation {
	String city;
	String postal_code;
	String latitude_e6;
	String longitude_e6;
	String forecast_date;
	String current_date_time;
	String unit_system;

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getPostal_code() {
		return postal_code;
	}

	public void setPostal_code(String postal_code) {
		this.postal_code = postal_code;
	}

	public String getLatitude_e6() {
		return latitude_e6;
	}

	public void setLatitude_e6(String latitude_e6) {
		this.latitude_e6 = latitude_e6;
	}

	public String getLongitude_e6() {
		return longitude_e6;
	}

	public void setLongitude_e6(String longitude_e6) {
		this.longitude_e6 = longitude_e6;
	}

	public String getForecast_date() {
		return forecast_date;
	}

	public void setForecast_date(String forecast_date) {
		this.forecast_date = forecast_date;
	}

	public String getCurrent_date_time() {
		return current_date_time;
	}

	public void setCurrent_date_time(String current_date_time) {
		this.current_date_time = current_date_time;
	}

	public String getUnit_system() {
		return unit_system;
	}

	public void setUnit_system(String unit_system) {
		this.unit_system = unit_system;
	}

}




}
第四个类也是最重要的核心类,这个需要按照所给xml结构写出来,代码里面有注释,不懂的可以留言

package mars.com;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class WeatherXmlService {
	// 声明list是将三个实体对象封装起来,返回到Activity
	static List<Object> objList = new ArrayList<Object>();
	static WeatherForecastInformation forecastInformation = null;// 预测信息
	static WeatherCurrentCondition currentCondition = null;// 当前情况
	static List<WeatherForecastCondition> forecastConditionList = null;// 预测天气的集合
	static WeatherForecastCondition forecastCondition = null;// 预测天气
	static XmlPullParser parser;
	static HttpClient client;
	static HttpPost post;
	static HttpResponse response;
	static HttpEntity httpEntity;

	public static List<Object> getWeatherInfos(String queryString)
			throws Exception {
		// 以下通过pull解析google服务器接口返回xml,分别组装到三个实体对象中
		parser = Xml.newPullParser();
		client = new DefaultHttpClient();
		post = new HttpPost(queryString);
		response = client.execute(post);
		httpEntity = response.getEntity();
		// 由于返回的数据是iso-8859-1所以此处需要转码
		String string = EntityUtils.toString(httpEntity, "UTF-8");
		InputStream inputStream = new ByteArrayInputStream(string.getBytes());
		parser.setInput(inputStream, "UTF-8");
		int event = parser.getEventType();
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_DOCUMENT:
				forecastConditionList = new ArrayList<WeatherForecastCondition>();
				break;
			case XmlPullParser.START_TAG:
				if ("forecast_information".equalsIgnoreCase(parser.getName())) {
					forecastInformation = new WeatherForecastInformation();
					break;
				} else if ("current_conditions".equalsIgnoreCase(parser
						.getName())) {
					currentCondition = new WeatherCurrentCondition();
					break;
				} else if ("forecast_conditions".equalsIgnoreCase(parser
						.getName())) {
					forecastCondition = new WeatherForecastCondition();
					break;
				}
				// 预测城市相关信息
				if (forecastInformation != null) {
					if ("city".equalsIgnoreCase(parser.getName())) {
						forecastInformation.setCity(parser.getAttributeValue(0));
					} else if ("postal_code".equalsIgnoreCase(parser.getName())) {
						forecastInformation.setPostal_code(parser
								.getAttributeValue(0));
					} else if ("latitude_e6".equalsIgnoreCase(parser.getName())) {
						forecastInformation.setLatitude_e6(parser
								.getAttributeValue(0));
					} else if ("longitude_e6"
							.equalsIgnoreCase(parser.getName())) {
						forecastInformation.setLongitude_e6(parser
								.getAttributeValue(0));
					} else if ("forecast_date".equalsIgnoreCase(parser
							.getName())) {
						forecastInformation.setForecast_date(parser
								.getAttributeValue(0));
					} else if ("current_date_time".equalsIgnoreCase(parser
							.getName())) {
						forecastInformation.setCurrent_date_time(parser
								.getAttributeValue(0));
					} else if ("unit_system".equalsIgnoreCase(parser.getName())) {
						forecastInformation.setUnit_system(parser
								.getAttributeValue(0));
					}
					break;
				}
				if (currentCondition != null) {
					if ("condition".equalsIgnoreCase(parser.getName())) {
						currentCondition.setCondition(parser
								.getAttributeValue(0));
					} else if ("temp_f".equalsIgnoreCase(parser.getName())) {
						currentCondition.setTemp_f(parser.getAttributeValue(0));
					} else if ("temp_c".equalsIgnoreCase(parser.getName())) {
						currentCondition.setTemp_c(parser.getAttributeValue(0));
					} else if ("humidity".equalsIgnoreCase(parser.getName())) {
						currentCondition.setHumidity(parser
								.getAttributeValue(0));
					} else if ("icon".equalsIgnoreCase(parser.getName())) {
						currentCondition
								.setIconURL(parser.getAttributeValue(0));
					} else if ("wind_condition".equalsIgnoreCase(parser
							.getName())) {
						currentCondition.setWind_condition(parser
								.getAttributeValue(0));
					}
					break;
				}
				if (forecastCondition != null) {
					if ("day_of_week".equalsIgnoreCase(parser.getName())) {
						forecastCondition.setDay_of_week(parser
								.getAttributeValue(0));
					} else if ("low".equalsIgnoreCase(parser.getName())) {
						forecastCondition.setLow(parser.getAttributeValue(0));
					} else if ("high".equalsIgnoreCase(parser.getName())) {
						forecastCondition.setHigh(parser.getAttributeValue(0));
					} else if ("icon".equalsIgnoreCase(parser.getName())) {
						forecastCondition.setIconURL(parser
								.getAttributeValue(0));
					} else if ("condition".equalsIgnoreCase(parser.getName())) {
						forecastCondition.setCondition(parser
								.getAttributeValue(0));
					}
					break;
				}
				break;
			case XmlPullParser.END_TAG:
				if ("forecast_information".equalsIgnoreCase(parser.getName())) {
					objList.add(forecastInformation);
				} else if ("current_conditions".equalsIgnoreCase(parser
						.getName())) {
					objList.add(currentCondition);
				} else if ("forecast_conditions".equalsIgnoreCase(parser
						.getName())) {
					forecastConditionList.add(forecastCondition);
				}
				if ("forecast_information".equalsIgnoreCase(parser.getName())
						|| "current_conditions".equalsIgnoreCase(parser
								.getName())
						|| "forecast_conditions".equalsIgnoreCase(parser
								.getName())) {
					forecastInformation = null;
					currentCondition = null;
					forecastCondition = null;
				}
				break;
			default:
				break;
			}
			event = parser.next();// 进入下一个元素并且触发相应事件
		}
		objList.add(forecastConditionList);
		if (inputStream != null) {
			inputStream.close();
		}
		return objList;
	}
}
// // 声明list是将三个实体对象封装起来,返回到Activity
// List<Object> objList = new ArrayList<Object>();
// WeatherForecastInformation forecastInformation = null;// 预测信息
// WeatherCurrentCondition currentCondition = null;// 当前情况
// List<WeatherForecastCondition> forecastConditionList = null;//
// 预测天气的集合
// WeatherForecastCondition forecastCondition = null;// 预测天气
// 以下通过pull解析google服务器接口返回xml,分别组装到三个实体对象中
// XmlPullParser parser = Xml.newPullParser();
// HttpClient client = new DefaultHttpClient();
// HttpPost post = new HttpPost(queryString);
// HttpResponse response = client.execute(post);
// HttpEntity httpEntity = response.getEntity();

3.基本工作算是完成了,咱们写写布局文件吧,弄得比较简单,如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- 用户可以输入拼音点击确定查询天气 -->

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/et_city"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:hint="请输入城市名:" />

        <Button
            android:id="@+id/bt_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="确定" />
    </LinearLayout>
    <!-- 显示当前和今天的天气情况 -->

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image_info1"
            android:layout_width="40dp"
            android:layout_height="40dp" />

        <TextView
            android:id="@+id/tv_info1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <!-- 显示未来三天的天气情况 -->

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image_info2"
            android:layout_width="40dp"
            android:layout_height="40dp" />

        <TextView
            android:id="@+id/tv_info2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image_info3"
            android:layout_width="40dp"
            android:layout_height="40dp" />

        <TextView
            android:id="@+id/tv_info3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image_info4"
            android:layout_width="40dp"
            android:layout_height="40dp" />

        <TextView
            android:id="@+id/tv_info4"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

4.最后再写activity,把你需要的提取出来,进行显示就行了。提取图片的时候,有两种方法,我试过了,都可以,只不过是一个代码少,不易读,一个代码多但是易读。开始我用的是代码少的,后来想清楚点,就用的是代码多的。我都贴出来了。如下

package mars.com;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

public class DemoWeatherPull extends Activity implements OnClickListener {
	private static final String weatherPath = "http://www.google.com/ig/api?weather=";
	private static final String googlePath = "http://www.google.com";
	private EditText et_city;
	private Button bt_city;
	private ImageView image_info1;
	private TextView tv_info1;
	private ImageView image_info2;
	private TextView tv_info2;
	private ImageView image_info3;
	private TextView tv_info3;
	private ImageView image_info4;
	private TextView tv_info4;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.initialize();
		bt_city.setOnClickListener(this);
	}

	public void onClick(View v) {
		try {
			String et_city_value = et_city.getText().toString();
			et_city_value = et_city_value == null ? "" : et_city_value;
			if (et_city_value.equals("")) {
				et_city_value = "beijing";
			}
			String queryString = weatherPath + et_city_value;
			List<Object> objs = WeatherXmlService.getWeatherInfos(queryString);
			if (objs != null && objs.size() == 3) {
				// 按照写入顺序读取
				WeatherForecastInformation forecastInformation = (WeatherForecastInformation) objs
						.get(0);// 当前预测城市相关信息

				WeatherCurrentCondition currentCondition = (WeatherCurrentCondition) objs
						.get(1);// 当前天气情况

				WeatherForecastCondition today = null;// 今天的预报情况
				List<WeatherForecastCondition> forecastConditionList = (List<WeatherForecastCondition>) objs
						.get(2);
				if (forecastConditionList != null
						&& forecastConditionList.size() > 0) {
					today = forecastConditionList.get(0);
				}
				DemoWeatherPull.this.setTitle(et_city_value + "的天气情况");
				image_info1.setImageBitmap(getBitmapByPath(googlePath
						+ currentCondition.getIconURL()));
				StringBuffer sb = new StringBuffer();
				sb.append("城市:" + forecastInformation.getCity() + "\n预测时间:"
						+ forecastInformation.getForecast_date() + "\n当前天气:"
						+ currentCondition.getCondition() + "\n当前湿度:"
						+ currentCondition.getHumidity() + "\n当前风度:"
						+ currentCondition.getWind_condition());
				if (today != null) {
					sb.append("\n星期:" + today.getDay_of_week());
					sb.append("\n最低温度:" + today.getLow() + "℃");
					sb.append("\n最高温度:" + today.getHigh() + "℃");
				}
				tv_info1.setText(sb.toString());
				for (int i = 0; i < forecastConditionList.size(); i++) {
					WeatherForecastCondition tmp = forecastConditionList.get(i);
					switch (i) {
					case 0:// 未来第一天就是今天,这里不再写
						break;
					case 1:
						image_info2.setImageBitmap(getBitmapByPath(googlePath
								+ tmp.getIconURL()));
						sb = new StringBuffer();
						sb.append("星期:" + tmp.getDay_of_week());
						sb.append("\n最低温度:" + tmp.getLow() + "℃");
						sb.append("\n最高温度:" + tmp.getHigh() + "℃");
						tv_info2.setText(sb.toString());
						break;
					case 2:
						image_info3.setImageBitmap(getBitmapByPath(googlePath
								+ tmp.getIconURL()));
						sb = new StringBuffer();
						sb.append("星期:" + tmp.getDay_of_week());
						sb.append("\n最低温度:" + tmp.getLow() + "℃");
						sb.append("\n最高温度:" + tmp.getHigh() + "℃");
						tv_info3.setText(sb.toString());
						break;
					case 3:
						image_info4.setImageBitmap(getBitmapByPath(googlePath
								+ tmp.getIconURL()));
						sb = new StringBuffer();
						sb.append("星期:" + tmp.getDay_of_week());
						sb.append("\n最低温度:" + tmp.getLow() + "℃");
						sb.append("\n最高温度:" + tmp.getHigh() + "℃");
						tv_info4.setText(sb.toString());
						break;
					default:
						break;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Bitmap getBitmapByPath(String path) throws IOException {
		 URL url = new URL(path);
		 Bitmap bm = BitmapFactory.decodeStream(url.openStream());
		 return bm;
//      下面进行图片的请求 并生成一幅bmp图像 
//		URL iconurl = new URL(path);
//		URLConnection conn = iconurl.openConnection();
//		conn.connect();
//		// 获得图像的字符流
//		InputStream is = conn.getInputStream();
//		BufferedInputStream bis = new BufferedInputStream(is, 8192);
//		Bitmap bm = null;// 生成了一张bmp图像
//		bm = BitmapFactory.decodeStream(bis);
//		bis.close();
//		is.close();// 关闭流
//		return bm;
	}

	private void initialize() {
		et_city = (EditText) findViewById(R.id.et_city);
		bt_city = (Button) findViewById(R.id.bt_city);
		image_info1 = (ImageView) findViewById(R.id.image_info1);
		tv_info1 = (TextView) findViewById(R.id.tv_info1);
		image_info2 = (ImageView) findViewById(R.id.image_info2);
		tv_info2 = (TextView) findViewById(R.id.tv_info2);
		image_info3 = (ImageView) findViewById(R.id.image_info3);
		tv_info3 = (TextView) findViewById(R.id.tv_info3);
		image_info4 = (ImageView) findViewById(R.id.image_info4);
		tv_info4 = (TextView) findViewById(R.id.tv_info4);
	}
}

5.第五步,我一般会给大家一个提醒,权限呀,亲,千万别忘记了。。。如下

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mars.com"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".DemoWeatherPull"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

如果你看完了,觉得还不错,挺一个吧。我以后会持续更新博客的。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值