设为首页 加入收藏

TOP

Android开发之Google天气显示(综合例子)(一)
2014-11-24 12:42:42 来源: 作者: 【 】 浏览:0
Tags:Android 开发 Google 天气 显示 综合 例子

1.生成url
2.获取google返回的网络信息 new InputSource(aURL.openStream())
3.生成解析xml的处理器
4.解析xml
5.封装解析后的xml文件
6.根据解析后的数据,生成url,获取google返回的天气图标,赋值给图片


代码:


/*获取用户输入的城市名称*/
String city = ((EditText) findViewById(R.id.input))
.getText().toString();

/*组成URL字符串*/
//中文:http://www.google.com/ig/api hl=zh-cn&weather=
//英文:http://www.google.com/ig/api weather=
String queryString = "http://www.google.com/ig/api weather="
+ city;
/*将可能的空格替换为"%20"*/
URL aURL = new URL(queryString.replace(" ", "%20"));

/* 从SAXParserFactory获取SAXParser*/
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();


/* 从SAXParser得到XMLReader*/
XMLReader xr = sp.getXMLReader();


/*
* 创建GoogleWeatherHandler,以便解析XML内容
*/
GoogleWeatherHandler gwh = new GoogleWeatherHandler();
xr.setContentHandler(gwh);


/* 解析XML文件内容 */
xr.parse(new InputSource(aURL.openStream()) );



TextView tv1 = (TextView)findViewById(R.id.tem);
tv1.setText("温度:" + gwh.getCurrentTemp() + "摄氏度");

TextView tv2 = (TextView)findViewById(R.id.weather);
tv2.setText(gwh.getCurrentCondition());

TextView tv3 = (TextView)findViewById(R.id.hum);
tv3.setText(""+ gwh.getCurrentHum() );


URL iconURL = new URL("http://www.google.com"+ gwh.getIconURL());
URLConnection conn = iconURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//设置icon
ImageView iv = (ImageView)findViewById(R.id.iconOfWeather);
Bitmap bm = null;
bm = BitmapFactory.decodeStream(bis);
iv.setImageBitmap(bm);
bis.close();
is.close();


分析google返回的xml的处理类代码:
private boolean in_current_conditions = false;
private boolean in_forecast_conditions = false;

private Integer current_temp;
private String current_condition;
private String current_hum;
private String iconURL;



@Override
public void startDocument() throws SAXException {

}


@Override
public void endDocument() throws SAXException {

}


@Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
// 'Outer' Tags
if (localName.equals("forecast_information")) {
this.in_forecast_information = true;
} else if (localName.equals("current_conditions")) {
this.i

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android系统移植 下一篇android开发之读取xml文件

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·常用meta整理 | 菜鸟 (2025-12-25 01:21:52)
·SQL HAVING 子句:深 (2025-12-25 01:21:47)
·SQL CREATE INDEX 语 (2025-12-25 01:21:45)
·Shell 传递参数 (2025-12-25 00:50:45)
·Linux echo 命令 - (2025-12-25 00:50:43)