DayOfWeek.java
package com.zhy.shortcut.test;
/**
* 周天气信息
* @author scott
*
*/
public class DayOfWeek {
private String day_of_week;
private String low;
private String high;
private String icon;
private String info;
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 getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
WeatherInfo.java
package com.zhy.shortcut.test;
/**
* 天气信息实体类
* @author scott
*
*/
public class WeatherInfo {
private String city;
private String time;
private String weatherinfo;
private String humidity;
private String image;
private String wind;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getWeatherinfo() {
return weatherinfo;
}
public void setWeatherinfo(String weatherinfo) {
this.weatherinfo = weatherinfo;
}
public String getHumidity() {
return humidity;
}
public void setHumidity(String humidity) {
this.humidity = humidity;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
}
WeatherActivity.java
package com.zhy.ui;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.zhy.shortcut.R;
import com.zhy.shortcut.test.DayOfWeek;
import com.zhy.shortcut.test.WeatherInfo;
public class WeatherActivity extends Activity {
//当天天气信息
private ImageView imageView;
private TextView city;
private TextView time;
private TextView weatherinfo;
private TextView humidity;
private TextView wind;
List<String> lists=null;
ListView listView;
Spinner spinner;
//用于SimpleAdaper时的参数 其数据为Map中的键
String[] from=new String[]{"icon","day_of_week","info","high","low"};
//存放控件的Id
int[] to=new int[]{R.id.icon,R.id.day_of_week,R.id.info,R.id.high,R.id.low};
Handler handlercity;
Handler handler=new Handler(){
WeatherInfo info=null;
List<DayOfWeek> list=null;
@SuppressWarnings("unchecked")
public void handleMessage(android.os.Message msg) {
//从Handler中取值,msg.obj中存放的是HashMap
HashMap<String, Object> map=(HashMap<String, Object>) msg.obj;
//从Map中获取当前天气信息
info=(WeatherInfo) map.get("info");
//从Map中获取DayOfWeek信息
list=(List<DayOfWeek>) map.get("list");
//设置当前天气信息
try {
imageView.setImageDrawable(Drawable.createFromStream(new URL(info.getImage()).openStream(), null));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
city.setText(info.getCity());
weatherinfo.setText(info.getWeatherinfo());
humidity.setText(info.getHumidity());
wind.setText(info.getWind());
time.setText(info.getTime());
//使用SimpleAdapter方式来处理天气数据
/*
List<HashMap<String, String>> lsit=new ArrayList<HashMap<String,String>>();
HashMap<String, String> maps=null;
for (DayOfWeek week : list) {
maps=new HashMap<String, String>();
maps.put("day_of_week", week.getDay_of_week());
maps.put("info", week.getInfo());
maps.put("icon", week.getIcon());
maps.put("high", week.getHigh());
maps.put("low", week.getLow());
lsit.add(maps);
}*/
//listView.setAdapter(new SimpleAdapter(WeatherActivity.this,lsit,R.layout.weatherlst,from,to));
//使用自定义的Adaper处理天气信息
listView.setAdapter(new WeatherAdapter(WeatherActivity.this,list));
};
};
Handler spanhandler=new Handler(){
WeatherInfo info=null;
List<DayOfWeek> list=null;
@SuppressWarnings("unchecked")
public void handleMessage(Message msg) {
//从Handler中取值,msg.obj中存放的是HashMap
HashMap<String, Object> map=(HashMap<String, Object>) msg.obj;
//从Map中获取当前天气信息
info=(WeatherInfo) map.get("info");
//从Map中获取DayOfWeek信息
list=(List<DayOfWeek>) map.get("list");
//设置当前天气信息
try {
imageView.setImageDrawable(Drawable.createFromStream(new URL(info.getImage()).openStream(), null));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
city.setText(info.getCity());
weatherinfo.setText(info.getWeatherinfo());
humidity.setText(info.getHumidity());
wind.setText(info.getWind());
time.setText(info.getTime());
//使用自定义的Adaper处理天气信息
listView.setAdapter(new WeatherAdapter(WeatherActivity.this,list));
}
};
/**
* 自定义的Adaper
* @author scott
*
*/
class WeatherAdapter extends BaseAdapter{
List<DayOfWeek> list;
public List<DayOfWeek> getList() {
return list;
}
public void setList(List<DayOfWeek> list) {
this.list = list;
}
Context context;
public WeatherAdapter() {
}
public WeatherAdapter(Context context,List<DayOfWeek> list) {
super();
this.context = context;
this.list=list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
//重点是这个方法
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//使用LayoutInflater加载xml布局文件
convertView = LayoutInflater.from(context).inflate(R.layout.weatherlst,null);
//查找控件 注意是从convertView中查找即新加载的xml布局文件中查找
ImageView viewImageView = (ImageView) convertView.findViewById(R.id.icon);
TextView day_of_week=(TextView) convertView.findViewById(R.id.day_of_week);
TextView info=(TextView) convertView.findViewById(R.id.info);
TextView high=(TextView) convertView.findViewById(R.id.high);
TextView low=(TextView) convertView.findViewById(R.id.low);
//设置数据
try {
viewImageView.setImageDrawable(Drawable.createFromStream(new URL(list.get(position).getIcon()).openStream(), null));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
day_of_week.setText(list.get(position).getDay_of_week());
info.setText(list.get(position).getInfo());
high.setText(list.get(position).getHigh());
low.setText(list.get(position).getLow());
//返回view
return convertView;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather);
imageView=(ImageView) findViewById(R.id.todayimg);
city=(TextView) findViewById(R.id.city);
time=(TextView) findViewById(R.id.time);
weatherinfo=(TextView) findViewById(R.id.weatherinfo);
humidity=(TextView) findViewById(R.id.humidity);
wind=(TextView) findViewById(R.id.wind);
spinner=(Spinner) findViewById(R.id.cities);
listView=(ListView) findViewById(R.id.lst);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
String city;
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
spanhandler.postDelayed(new Runnable() {
//调用解析天气预报的代码
@Override
public void run() {
city=spinner.getSelectedItem().toString();
String urlString="http://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode(city);;
try {
URL url=new URL(urlString);
try {
URLConnection connection=url.openConnection();
InputStream inputStream = connection.getInputStream();
try {
//调用Google天气预报解析方法
HashMap<String, Object> map = parse(inputStream);
Message msg=new Message();
//传递数据
msg.obj=map;
//发送消息
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
},2000);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
handlercity=new Handler();
handlercity.post(new Runnable() {
@Override
public void run() {
try {
lists = parse();
} catch (Exception ex) {
ex.printStackTrace();
}
//创建adapter
ArrayAdapter<String> adapter=new ArrayAdapter<String>(WeatherActivity.this, android.R.layout.simple_spinner_item, lists);
spinner.setAdapter(adapter);
//查找西安的位置
int position=lists.indexOf("西安");
//设置默认选中西安
spinner.setSelection(position);
//设置下拉列别的样式
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
}
});
handler.post(new Runnable() {
//调用解析天气预报的代码
@Override
public void run() {
String urlString="http://www.google.com/ig/api?hl=zh-cn&weather="+URLEncoder.encode("西安");
try {
URL url=new URL(urlString);
try {
URLConnection connection=url.openConnection();
InputStream inputStream = connection.getInputStream();
try {
//调用Google天气预报解析方法
HashMap<String, Object> map = parse(inputStream);
Message msg=new Message();
//传递数据
msg.obj=map;
//发送消息
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
}
/**
* 解析Goole天气预报返回的xml数据
* @param inputStream
* @throws Exception
*/
private HashMap<String, Object> parse(InputStream inputStream) throws Exception {
WeatherInfo info=null;
DayOfWeek dayOfWeek=null;
List<DayOfWeek> list=null;
HashMap<String, Object> map=new HashMap<String, Object>();
boolean isFirst=true;
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(inputStream, "gbk");
int eventType=parser.getEventType();
while(eventType!=XmlPullParser.END_DOCUMENT){
String nodename=parser.getName();
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
list=new ArrayList<DayOfWeek>();
case XmlPullParser.START_TAG:
if(isFirst){
if("forecast_information".equals(nodename)){
info=new WeatherInfo();
}
if("city".equals(nodename)){
info.setCity(parser.getAttributeValue(0));
}if("forecast_date".equals(nodename)){
info.setTime(parser.getAttributeValue(0));
}if("condition".equals(nodename)){
info.setWeatherinfo(parser.getAttributeValue(0));
}if("humidity".equals(nodename)){
info.setHumidity(parser.getAttributeValue(0));
}if("icon".equals(nodename)){
info.setImage("http://www.google.com"+parser.getAttributeValue(0));
}if("wind_condition".equals(nodename)){
info.setWind(parser.getAttributeValue(0));
}
}else{
if("forecast_conditions".equals(nodename)){
dayOfWeek=new DayOfWeek();
}
if("day_of_week".equals(nodename)){
dayOfWeek.setDay_of_week(parser.getAttributeValue(0));
}if("low".equals(nodename)){
dayOfWeek.setLow(parser.getAttributeValue(0));
}if("high".equals(nodename)){
dayOfWeek.setHigh(parser.getAttributeValue(0));
}if("icon".equals(nodename)){
dayOfWeek.setIcon("http://www.google.com"+parser.getAttributeValue(0));
}if("condition".equals(nodename)){
dayOfWeek.setInfo(parser.getAttributeValue(0));
}
}
break;
case XmlPullParser.END_TAG:
if("current_conditions".equals(nodename)){
isFirst=false;
}
if("forecast_conditions".equals(nodename)){
list.add(dayOfWeek);
}
break;
default:
break;
}
eventType=parser.next();
}
map.put("info", info);
map.put("list", list);
return map;
}
/**
* 解析城市
* @return
* @throws Exception
*/
private List<String> parse() throws Exception{
List<String> list=new ArrayList<String>();
String urlString = "http://www.google.com/ig/cities?country=cn&hl=zh-cn";
URL url=new URL(urlString);
InputStream inputStream= url.openStream();
StringBuilder json=new StringBuilder();
String str;
BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream,"gbk"));
while((str=reader.readLine())!=null){
json.append(str);
}
JSONObject jsonObject=new JSONObject(json.toString());
JSONArray array = jsonObject.getJSONArray("cities");
for (int i = 0; i < array.length(); i++) {
JSONObject object=new JSONObject(array.getString(i));
String citys = (String)object.get("name");
list.add(citys);
}
reader.close();
inputStream.close();
return list;
}
}
weather.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/cities"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/todayimg"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/city"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/time"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/weatherinfo"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/humidity"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/wind"
/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lst"
>
</ListView>
</LinearLayout>
weatherlst.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<ImageView
android:paddingLeft="50dip"
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_toRightOf="@id/icon"
android:paddingLeft="10dip"
android:paddingTop="10dip">
<TextView
android:id="@+id/day_of_week"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="10dip" />
<TextView
android:id="@+id/info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="10dip" />
<TextView
android:id="@+id/low"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="10dip" />
<TextView
android:id="@+id/high"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="10dip" />
</LinearLayout>
</RelativeLayout>
</LinearLayout>
程序运行截图