cityweather

运行效果图

cityweather_第1张图片

代码如下:

CityWeather
package com.yarin.android.CityWeather;

import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

public class CityWeather extends Activity
{
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}


	private void init()
	{
		Spinner city_spr = (Spinner) findViewById(R.id.Spinner01);
		ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, ConstData.city);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		city_spr.setAdapter(adapter);

		Button submit = (Button) findViewById(R.id.Button01);
		submit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub

				Spinner spr = (Spinner) findViewById(R.id.Spinner01);
				Long l = spr.getSelectedItemId();
				int index = l.intValue();
				String cityParamString = ConstData.cityCode[index];

				try
				{
					URL url = new URL(ConstData.queryString + cityParamString);
					getCityWeather(url);
				}
				catch (Exception e)
				{
					Log.e("CityWeather", e.toString());
				}
				
			}
		});
		
		Button submit_input = (Button) findViewById(R.id.Button001);
		submit_input.setOnClickListener(new OnClickListener()
        {
			public void onClick(View v) 
			{
				EditText inputcity = (EditText) findViewById(R.id.EditText001);
				String tmp = inputcity.getText().toString();
				
				try
				{
					URL url = new URL(ConstData.queryString_intput + tmp);
					getCityWeather(url);
				}
				catch (Exception e)
				{
					Log.e("CityWeather", e.toString());
				}
			}
        	
        });
	}


	// 更新显示实时天气信息
	private void updateWeatherInfoView(int aResourceID, WeatherCurrentCondition aWCC) throws MalformedURLException
	{

		URL imgURL = new URL("http://www.google.com/" + aWCC.getIcon());
		((SingleWeatherInfoView) findViewById(aResourceID)).setWeatherIcon(imgURL);
		((SingleWeatherInfoView) findViewById(aResourceID)).setWeatherString(aWCC.toString());
	}


	// 更新显示天气预报
	private void updateWeatherInfoView(int aResourceID, WeatherForecastCondition aWFC) throws MalformedURLException
	{

		URL imgURL = new URL("http://www.google.com/" + aWFC.getIcon());
		((SingleWeatherInfoView) findViewById(aResourceID)).setWeatherIcon(imgURL);
		((SingleWeatherInfoView) findViewById(aResourceID)).setWeatherString(aWFC.toString());
	}
	
	//获取天气信息
	//通过网络获取数据
	//传递给XMLReader解析
	public void getCityWeather(URL url)
	{
		try
		{
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();

			XMLReader xr = sp.getXMLReader();

			GoogleWeatherHandler gwh = new GoogleWeatherHandler();
			xr.setContentHandler(gwh);

			InputStreamReader isr = new InputStreamReader(url.openStream(), "GBK");
			InputSource is = new InputSource(isr);

			xr.parse(is);

			WeatherSet ws = gwh.getMyWeatherSet();

			updateWeatherInfoView(R.id.weather_0, ws.getMyCurrentCondition());
			updateWeatherInfoView(R.id.weather_1, ws.getMyForecastConditions().get(0));
			updateWeatherInfoView(R.id.weather_2, ws.getMyForecastConditions().get(1));
			updateWeatherInfoView(R.id.weather_3, ws.getMyForecastConditions().get(2));
			updateWeatherInfoView(R.id.weather_4, ws.getMyForecastConditions().get(3));
		}
		catch (Exception e)
		{
			Log.e("CityWeather", e.toString());
		}
	}
}
ConstData
package com.yarin.android.CityWeather;

public class ConstData
{
	public static final String queryString="http://www.google.com/ig/api?hl=zh-cn&weather=,,,";
	public static final String queryString_intput="http://www.google.com/ig/api?hl=zh_cn&weather=";
	public static final String [] cityCode ={
    		"39930000,116279998",//北京
    		"31399999,121470001",//上海
    		"39099998,117169998",//天津
    		"29520000,106480003",//重庆
    		"39669998,118150001",//唐山
    		"38029998,114419998",//石家庄
    		"38900001,121629997",//大连
    		"45750000,126769996",//哈尔滨
    		"20030000,110349998",//海口
    		"43900001,125220001",//长春
    		"28229999,112870002",//长沙
    		"30670000,104019996",//成都
    		"26079999,119279998",//福州
    		"23129999,113319999",//广州
    		"26579999,106720001",//贵阳
    		"30229999,120169998",//杭州
    		"31870000,117230003",//合肥
    		"40819999,111680000",//呼和浩特
    		"36680000,116980003",//济南
    		"25020000,102680000",//昆明
    		"29657589,91132050",//拉萨
    		"36040000,103879997",//兰州
    		"28600000,115919998",//南昌
    		"32000000,118800003",//南京
    		"22819999,108349998",//南宁
    		"36069999,120330001",//青岛
    		"22549999,114099998",//深圳
    		"41770000,123430000",//沈阳
    		"37779998,112550003",//太原
    		"43779998,87620002",//乌鲁木齐
    		"30620000,114129997",//武汉
    		"34299999,108930000",//西安
    		"36619998,101769996",//西宁
    		"24479999,118080001",//厦门
    		"34279998,117150001",//徐州
    		"38479999,106220001",//银川
    		"34720001,113650001"//郑州
    };
    public static final String [] city ={
		"北京",//
		"上海",//
		"天津",//
		"重庆",//
		"唐山",//
		"石家庄",//
		"大连",//
		"哈尔滨",//
		"海口",//
		"长春",//
		"长沙",//
		"成都",//
		"福州",//
		"广州",//
		"贵阳",//
		"杭州",//
		"合肥",//
		"呼和浩特",//
		"济南",//
		"昆明",//
		"拉萨",//
		"兰州",//
		"南昌",//
		"南京",//
		"南宁",//
		"青岛",//
		"深圳",//
		"沈阳",//
		"太原",//
		"乌鲁木齐",//
		"武汉",//
		"西安",//
		"西宁",//
		"厦门",//
		"徐州",//
		"银川",//
		"郑州"//
    };
}

GoogleWeatherHandler
package com.yarin.android.CityWeather;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

/**

-
-
 
 
 
 
 
 
 
 
-
 
 
 
 
 
 
 
-
 
 
 
 
 
 
-
 
 
 
 
 
 
-
 
 
 
 
 
 
-
 
 
 
 
 
 
 
 
 */
public class GoogleWeatherHandler extends DefaultHandler
{
	//天气信息
	private WeatherSet		myWeatherSet			= null;

	//实时天气信息
	private boolean			is_Current_Conditions	= false;
	//预报天气信息
	private boolean			is_Forecast_Conditions	= false;

	private final String	CURRENT_CONDITIONS		= "current_conditions";
	private final String	FORECAST_CONDITIONS		= "forecast_conditions";


	public GoogleWeatherHandler()
	{

	}


	//返回天气信息对象
	public WeatherSet getMyWeatherSet()
	{
		return myWeatherSet;
	}


	@Override
	public void endDocument() throws SAXException
	{
		// TODO Auto-generated method stub
		super.endDocument();
	}


	@Override
	public void endElement(String uri, String localName, String name) throws SAXException
	{

		if (localName.equals(CURRENT_CONDITIONS))
		{
			this.is_Current_Conditions = false;
		}
		else if (localName.equals(FORECAST_CONDITIONS))
		{
			this.is_Forecast_Conditions = false;
		}
	}


	@Override
	public void startDocument() throws SAXException
	{
		this.myWeatherSet = new WeatherSet();
	}


	@Override
	public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException
	{
		if (localName.equals(CURRENT_CONDITIONS))
		{//实时天气
			Log.i("localName+CURRENT", localName);
			this.myWeatherSet.setMyCurrentCondition(new WeatherCurrentCondition());
			Log.i("localName+CURRENT+1", localName);
			this.is_Current_Conditions = true;
		}
		else if (localName.equals(FORECAST_CONDITIONS))
		{//预报天气
			this.myWeatherSet.getMyForecastConditions().add(new WeatherForecastCondition());
			this.is_Forecast_Conditions = true;
		}
		else
		{
			//分别将得到的信息设置到指定的对象中
			if (localName.equals(CURRENT_CONDITIONS))
			{
				Log.i("localName+CURRENT", localName);
			}
			String dataAttribute = attributes.getValue("data");
			
			if (localName.equals("icon"))
			{
				if (this.is_Current_Conditions)
				{
					this.myWeatherSet.getMyCurrentCondition().setIcon(dataAttribute);
				}
				else if (this.is_Forecast_Conditions)
				{
					this.myWeatherSet.getLastForecastCondition().setIcon(dataAttribute);
				}
			}
			else if (localName.equals("condition"))
			{
				if (this.is_Current_Conditions)
				{
					this.myWeatherSet.getMyCurrentCondition().setCondition(dataAttribute);
				}
				else if (this.is_Forecast_Conditions)
				{
					this.myWeatherSet.getLastForecastCondition().setCondition(dataAttribute);
				}
			}
			else if (localName.equals("temp_c"))
			{
				this.myWeatherSet.getMyCurrentCondition().setTemp_celcius(dataAttribute);
			}
			else if (localName.equals("temp_f"))
			{
				this.myWeatherSet.getMyCurrentCondition().setTemp_fahrenheit(dataAttribute);
			}
			else if (localName.equals("humidity"))
			{
				this.myWeatherSet.getMyCurrentCondition().setHumidity(dataAttribute);
			}
			else if (localName.equals("wind_condition"))
			{
				this.myWeatherSet.getMyCurrentCondition().setWind_condition(dataAttribute);
			}// Tags is forecast_conditions
			else if (localName.equals("day_of_week"))
			{
				this.myWeatherSet.getLastForecastCondition().setDay_of_week(dataAttribute);
			}
			else if (localName.equals("low"))
			{
				this.myWeatherSet.getLastForecastCondition().setLow(dataAttribute);
			}
			else if (localName.equals("high"))
			{
				this.myWeatherSet.getLastForecastCondition().setHigh(dataAttribute);
			}
		}
	}


	@Override
	public void characters(char ch[], int start, int length)
	{
		/*
		 * Would be called on the following structure:
		 * characters
		 */
	}
}

 
  
SingleWeatherInfoView
package com.yarin.android.CityWeather;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class SingleWeatherInfoView extends LinearLayout
{
	private ImageView	myWeatherImageView	= null;
	private TextView	myTempTextView		= null;


	public SingleWeatherInfoView(Context context)
	{
		super(context);
	}


	public SingleWeatherInfoView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		
		this.myWeatherImageView = new ImageView(context);
		this.myWeatherImageView.setPadding(10, 5, 5, 5);

		this.myTempTextView = new TextView(context);
		this.myTempTextView.setTextColor(R.color.black);
		this.myTempTextView.setTextSize(16);

		this.addView(this.myWeatherImageView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		this.addView(this.myTempTextView, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	}


	public void setWeatherString(String aWeatherString)
	{
		this.myTempTextView.setText(aWeatherString);
	}


	public void setWeatherIcon(URL aURL){
		try{
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			Bitmap bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
			this.myWeatherImageView.setImageBitmap(bm);
		}catch (Exception e){}
	}
}
WeatherCurrentCondition
package com.yarin.android.CityWeather;
//实时天气信息处理(当前天气信息)
/**








*/

public class WeatherCurrentCondition
{

	private String	condition;			// 多云
	private String	temp_celcius;		// 摄氏温度
	private String	temp_fahrenheit;	// 华氏温度
	private String	humidity;			// 湿度:58%
	private String	wind_condition;		// 风向...
	private String	icon;				// 图标


	public WeatherCurrentCondition()
	{

	}


	//得到Condition(多云)
	public String getCondition()
	{
		return condition;
	}

	//设置Condition(多云)
	public void setCondition(String condition)
	{
		this.condition = condition;
	}

	//得到设置温度
	public String getTemp_c()
	{
		return temp_celcius;
	}

	//得到华氏温度
	public String getTemp_f()
	{
		return temp_fahrenheit;
	}

	//设置摄氏温度
	public void setTemp_celcius(String temp_celcius)
	{
		this.temp_celcius = temp_celcius;
	}

	//设置华氏温度
	public void setTemp_fahrenheit(String temp_fahrenheit)
	{
		this.temp_fahrenheit = temp_fahrenheit;
	}

	//得到(湿度:58%)
	public String getHumidity()
	{
		return humidity;
	}

	//设置(湿度:58%)
	public void setHumidity(String humidity)
	{
		this.humidity = humidity;
	}

	//得到风向指示
	public String getWind_condition()
	{
		return wind_condition;
	}

	//设置风向指示
	public void setWind_condition(String wind_condition)
	{
		this.wind_condition = wind_condition;
	}

	//得到图标地址
	public String getIcon()
	{
		return icon;
	}

	//设置图标地址
	public void setIcon(String icon)
	{
		this.icon = icon;
	}

	//得到一个封装打包的字符串,包括除icno外的所有东西
	public String toString()
	{
		StringBuilder sb = new StringBuilder();
		sb.append("实时天气: ").append(temp_celcius).append(" °C");
		sb.append(" ").append(temp_fahrenheit).append(" F");
		sb.append(" ").append(condition);
		sb.append(" ").append(humidity);
		sb.append(" ").append(wind_condition);
		return sb.toString();
	}
}
WeatherForecastCondition
package com.yarin.android.CityWeather;

//预报后四天的天气信息
/**







*/
public class WeatherForecastCondition {
	
	private String day_of_week;		//星期
	private String low;				//最低温度
	private String high;			//最高温度
	private String icon;			//图标
	private String condition;		//提示
	
	public WeatherForecastCondition()
	{

	}


	public String getCondition()
	{
		return condition;
	}


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


	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 toString()
	{
		StringBuilder sb = new StringBuilder();

		sb.append(" ").append(day_of_week);
		sb.append(" : ").append(high);
		sb.append("/").append(low).append(" °C");
		sb.append(" ").append(condition);
		return sb.toString();
	}
}
WeatherSet
package com.yarin.android.CityWeather;

import java.util.ArrayList;

public class WeatherSet
{
	//实时天气信息
	private WeatherCurrentCondition myCurrentCondition = null; 
	//预报的后四天的天气信息
    private ArrayList myForecastConditions = 
         							new ArrayList();
    
    public WeatherSet()
	{

	}
    
    //得到实时天气信息的对象
	public WeatherCurrentCondition getMyCurrentCondition()
	{
		return myCurrentCondition;
	}

	//设置实时天气信息的对象
	public void setMyCurrentCondition(WeatherCurrentCondition myCurrentCondition)
	{
		this.myCurrentCondition = myCurrentCondition;
	}

	//得到预报天气
	public ArrayList getMyForecastConditions()
	{
		return myForecastConditions;
	}

	//得到最后一个预报天气
	//这里我们每次添加一个数据都是在最后
	//所以得到最后一个
	public WeatherForecastCondition getLastForecastCondition()
	{
		return myForecastConditions.get(myForecastConditions.size() - 1);
	}
}


main.xml


	
	
		
			
			
			
		
	
	
		
			
			
			
		
	
	
		
			
		
		
			
		
		
			
		
		
			
		
		
			
		
	



你可能感兴趣的:(移动开发)