Android天气预报

这个项目是基于webservice的,用ksoap2来解析网络上的WebService的,我们先看做出的效果图

其实也没有很多技术难题,我们直接来看源码再做说明吧

  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. import org.ksoap2.SoapEnvelope;  
  5. import org.ksoap2.serialization.SoapObject;  
  6. import org.ksoap2.serialization.SoapSerializationEnvelope;  
  7. import org.ksoap2.transport.HttpTransportSE;  
  8.   
  9. public class WebServiceUtil  
  10. {  
  11.     // 定义Web Service的命名空间   
  12.     static final String SERVICE_NS = "http://WebXml.com.cn/";  
  13.     // 定义Web Service提供服务的URL   
  14.     static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";  
  15.   
  16.     /** 
  17.      * 获得州,国内外省份和城市信息 
  18.      *  
  19.      * @return 
  20.      */  
  21.     public static List<String> getProvinceList()  
  22.     {  
  23.   
  24.         // 需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)   
  25.         String methodName = "getRegionProvince";  
  26.         // 创建HttpTransportSE传输对象   
  27.         HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);  
  28.   
  29.         httpTranstation.debug = true;  
  30.         // 使用SOAP1.1协议创建Envelop对象   
  31.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  32.                 SoapEnvelope.VER11);  
  33.         // 实例化SoapObject对象   
  34.         SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);  
  35.         envelope.bodyOut = soapObject;  
  36.         // 设置与.Net提供的Web Service保持较好的兼容性   
  37.         envelope.dotNet = true;  
  38.         try  
  39.         {  
  40.             // 调用Web Service   
  41.             httpTranstation.call(SERVICE_NS + methodName, envelope);  
  42.             if (envelope.getResponse() != null)  
  43.             {  
  44.                 // 获取服务器响应返回的SOAP消息   
  45.                 SoapObject result = (SoapObject) envelope.bodyIn;  
  46.                 SoapObject detail = (SoapObject) result.getProperty(methodName  
  47.                         + "Result");  
  48.                 // 解析服务器响应的SOAP消息。   
  49.                 return parseProvinceOrCity(detail);  
  50.             }  
  51.         } catch (Exception e)  
  52.         {  
  53.             e.printStackTrace();  
  54.         }  
  55.   
  56.         return null;  
  57.     }  
  58.   
  59.     /** 
  60.      * 根据省份获取城市列表 
  61.      *  
  62.      * @param province 
  63.      * @return 
  64.      */  
  65.     public static List<String> getCityListByProvince(String province)  
  66.     {  
  67.   
  68.         // 需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)   
  69.         String methodName = "getSupportCityString";  
  70.           
  71.         HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);  
  72.         httpTranstation.debug = true;  
  73.           
  74.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  75.                 SoapEnvelope.VER11);  
  76.   
  77.         SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);  
  78.         soapObject.addProperty("theRegionCode", province);  
  79.         envelope.bodyOut = soapObject;  
  80.         envelope.dotNet = true;  
  81.         try  
  82.         {  
  83.             // 调用Web Service   
  84.             httpTranstation.call(SERVICE_NS + methodName, envelope);  
  85.             if (envelope.getResponse() != null)  
  86.             {  
  87.                 // 获取服务器响应返回的SOAP消息   
  88.                 SoapObject result = (SoapObject) envelope.bodyIn;  
  89.                 SoapObject detail = (SoapObject) result.getProperty(methodName  
  90.                         + "Result");  
  91.                 // 解析服务器响应的SOAP消息。   
  92.                 return parseProvinceOrCity(detail);  
  93.             }  
  94.         } catch (Exception e)  
  95.         {  
  96.             e.printStackTrace();  
  97.         }  
  98.   
  99.         return null;  
  100.   
  101.     }  
  102.   
  103.     private static List<String> parseProvinceOrCity(SoapObject detail)  
  104.     {  
  105.         ArrayList<String> result = new ArrayList<String>();  
  106.         for (int i = 0; i < detail.getPropertyCount(); i++)  
  107.         {  
  108.             String str = detail.getProperty(i).toString();  
  109.             // 解析出每个省份   
  110.             result.add(str.split(",")[0]);  
  111.         }  
  112.         return result;  
  113.     }  
  114.   
  115.     public static SoapObject getWeatherByCity(String cityName)  
  116.     {  
  117.   
  118.         // 根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数   
  119.         String methodName = "getWeather";  
  120.           
  121.         HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);  
  122.         httpTranstation.debug = true;  
  123.           
  124.         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
  125.                 SoapEnvelope.VER11);  
  126.         SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);  
  127.         soapObject.addProperty("theCityCode", cityName);  
  128.         envelope.bodyOut = soapObject;  
  129.         envelope.dotNet = true;  
  130.           
  131.         try  
  132.         {  
  133.             // 调用Web Service   
  134.             httpTranstation.call(SERVICE_NS + methodName, envelope);  
  135.             if (envelope.getResponse() != null)  
  136.             {  
  137.                 // 获取服务器响应返回的SOAP消息   
  138.                 SoapObject result = (SoapObject) envelope.bodyIn;  
  139.                 SoapObject detail = (SoapObject) result.getProperty(methodName  
  140.                         + "Result");  
  141.                 // 解析服务器响应的SOAP消息。   
  142.                 return detail;  
  143.             }  
  144.         } catch (Exception e)  
  145.         {  
  146.             e.printStackTrace();  
  147.         }  
  148.   
  149.         return null;  
  150.     }  
  151.   
  152. }  
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class WebServiceUtil
{
	// 定义Web Service的命名空间
	static final String SERVICE_NS = "http://WebXml.com.cn/";
	// 定义Web Service提供服务的URL
	static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";

	/**
	 * 获得州,国内外省份和城市信息
	 * 
	 * @return
	 */
	public static List<String> getProvinceList()
	{

		// 需要调用的方法名(获得本天气预报Web Services支持的洲、国内外省份和城市信息)
		String methodName = "getRegionProvince";
		// 创建HttpTransportSE传输对象
		HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);

		httpTranstation.debug = true;
		// 使用SOAP1.1协议创建Envelop对象
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		// 实例化SoapObject对象
		SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
		envelope.bodyOut = soapObject;
		// 设置与.Net提供的Web Service保持较好的兼容性
		envelope.dotNet = true;
		try
		{
			// 调用Web Service
			httpTranstation.call(SERVICE_NS + methodName, envelope);
			if (envelope.getResponse() != null)
			{
				// 获取服务器响应返回的SOAP消息
				SoapObject result = (SoapObject) envelope.bodyIn;
				SoapObject detail = (SoapObject) result.getProperty(methodName
						+ "Result");
				// 解析服务器响应的SOAP消息。
				return parseProvinceOrCity(detail);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 根据省份获取城市列表
	 * 
	 * @param province
	 * @return
	 */
	public static List<String> getCityListByProvince(String province)
	{

		// 需要调用的方法名(获得本天气预报Web Services支持的城市信息,根据省份查询城市集合:带参数)
		String methodName = "getSupportCityString";
		
		HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);
		httpTranstation.debug = true;
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);

		SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
		soapObject.addProperty("theRegionCode", province);
		envelope.bodyOut = soapObject;
		envelope.dotNet = true;
		try
		{
			// 调用Web Service
			httpTranstation.call(SERVICE_NS + methodName, envelope);
			if (envelope.getResponse() != null)
			{
				// 获取服务器响应返回的SOAP消息
				SoapObject result = (SoapObject) envelope.bodyIn;
				SoapObject detail = (SoapObject) result.getProperty(methodName
						+ "Result");
				// 解析服务器响应的SOAP消息。
				return parseProvinceOrCity(detail);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;

	}

	private static List<String> parseProvinceOrCity(SoapObject detail)
	{
		ArrayList<String> result = new ArrayList<String>();
		for (int i = 0; i < detail.getPropertyCount(); i++)
		{
			String str = detail.getProperty(i).toString();
			// 解析出每个省份
			result.add(str.split(",")[0]);
		}
		return result;
	}

	public static SoapObject getWeatherByCity(String cityName)
	{

		// 根据城市或地区名称查询获得未来三天内天气情况、现在的天气实况、天气和生活指数
		String methodName = "getWeather";
		
		HttpTransportSE httpTranstation = new HttpTransportSE(SERVICE_URL);
		httpTranstation.debug = true;
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
		soapObject.addProperty("theCityCode", cityName);
		envelope.bodyOut = soapObject;
		envelope.dotNet = true;
		
		try
		{
			// 调用Web Service
			httpTranstation.call(SERVICE_NS + methodName, envelope);
			if (envelope.getResponse() != null)
			{
				// 获取服务器响应返回的SOAP消息
				SoapObject result = (SoapObject) envelope.bodyIn;
				SoapObject detail = (SoapObject) result.getProperty(methodName
						+ "Result");
				// 解析服务器响应的SOAP消息。
				return detail;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}

		return null;
	}

}

 这里面有三个方法,分别解析了省份,城市,还有就是天气情况数据,这里面就采用了WebService来进行数据交互

接下来就是Activity中的代码:

  1. import java.util.List;  
  2.   
  3. import org.ksoap2.serialization.SoapObject;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.content.DialogInterface;  
  8. import android.content.SharedPreferences;  
  9. import android.os.Bundle;  
  10. import android.view.LayoutInflater;  
  11. import android.view.View;  
  12. import android.view.Window;  
  13. import android.widget.AdapterView;  
  14. import android.widget.AdapterView.OnItemSelectedListener;  
  15. import android.widget.ArrayAdapter;  
  16. import android.widget.Button;  
  17. import android.widget.ImageView;  
  18. import android.widget.Spinner;  
  19. import android.widget.TextView;  
  20. import android.widget.Toast;  
  21.   
  22. import com.kang.net.WebServiceUtil;  
  23.   
  24. public class WeatherWebServiceActivity extends Activity  
  25. {  
  26.     private TextView text;  
  27.     private Button city_btn;  
  28.     private static final int CITY = 0x11;  
  29.     private String city_str;  
  30.     private TextView city_text;  
  31.     private Spinner province_spinner;  
  32.     private Spinner city_spinner;  
  33.     private List<String> provinces;  
  34.     private List<String> citys;  
  35.     private SharedPreferences preference;  
  36.   
  37.     /** Called when the activity is first created. */  
  38.     @Override  
  39.     public void onCreate(Bundle savedInstanceState)  
  40.     {  
  41.         super.onCreate(savedInstanceState);  
  42.   
  43.         this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏   
  44.   
  45.         setContentView(R.layout.main);  
  46.           
  47.         preference = getSharedPreferences("weather", MODE_PRIVATE);  
  48.         city_str = readSharpPreference();  
  49.   
  50.         city_text = (TextView) findViewById(R.id.city);  
  51.         city_text.setText(city_str);  
  52.   
  53.         text = (TextView) findViewById(R.id.test);  
  54.   
  55.         city_btn = (Button) findViewById(R.id.city_button);  
  56.   
  57.         city_btn.setOnClickListener(new ClickEvent());  
  58.   
  59.         findViewById(R.id.content_today_layout).getBackground().setAlpha(120);  
  60.         findViewById(R.id.content_small_bg1).getBackground().setAlpha(120);  
  61.         findViewById(R.id.content_small_bg2).getBackground().setAlpha(120);  
  62.         findViewById(R.id.content_small_bg3).getBackground().setAlpha(120);  
  63.           
  64.         refresh(city_str);  
  65.   
  66.     }  
  67.   
  68.     class ClickEvent implements View.OnClickListener  
  69.     {  
  70.   
  71.         @Override  
  72.         public void onClick(View v)  
  73.         {  
  74.             switch (v.getId())  
  75.             {  
  76.             case R.id.city_button:  
  77.   
  78.                 show_dialog(CITY);  
  79.   
  80.                 break;  
  81.   
  82.             default:  
  83.                 break;  
  84.             }  
  85.   
  86.         }  
  87.   
  88.     }  
  89.   
  90.     public void showTast(String string)  
  91.     {  
  92.         Toast.makeText(WeatherWebServiceActivity.this, string, 1).show();  
  93.   
  94.     }  
  95.   
  96.     public void show_dialog(int cityId)  
  97.     {  
  98.   
  99.         switch (cityId)  
  100.         {  
  101.         case CITY:  
  102.   
  103.             // 取得city_layout.xml中的视图   
  104.             final View view = LayoutInflater.from(this).inflate(  
  105.                     R.layout.city_layout, null);  
  106.   
  107.             // 省份Spinner   
  108.             province_spinner = (Spinner) view  
  109.                     .findViewById(R.id.province_spinner);  
  110.             // 城市Spinner   
  111.             city_spinner = (Spinner) view.findViewById(R.id.city_spinner);  
  112.   
  113.             // 省份列表   
  114.             provinces = WebServiceUtil.getProvinceList();  
  115.   
  116.             ArrayAdapter adapter = new ArrayAdapter(this,  
  117.                     android.R.layout.simple_spinner_item, provinces);  
  118.             adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
  119.   
  120.             province_spinner.setAdapter(adapter);  
  121.             // 省份Spinner监听器   
  122.             province_spinner  
  123.                     .setOnItemSelectedListener(new OnItemSelectedListener()  
  124.                     {  
  125.   
  126.                         @Override  
  127.                         public void onItemSelected(AdapterView<?> arg0,  
  128.                                 View arg1, int position, long arg3)  
  129.                         {  
  130.   
  131.                             citys = WebServiceUtil  
  132.                                     .getCityListByProvince(provinces  
  133.                                             .get(position));  
  134.                             ArrayAdapter adapter1 = new ArrayAdapter(  
  135.                                     WeatherWebServiceActivity.this,  
  136.                                     android.R.layout.simple_spinner_item, citys);  
  137.                             adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);  
  138.                             city_spinner.setAdapter(adapter1);  
  139.   
  140.                         }  
  141.   
  142.                         @Override  
  143.                         public void onNothingSelected(AdapterView<?> arg0)  
  144.                         {  
  145.   
  146.                         }  
  147.                     });  
  148.   
  149.             // 城市Spinner监听器   
  150.             city_spinner.setOnItemSelectedListener(new OnItemSelectedListener()  
  151.             {  
  152.   
  153.                 @Override  
  154.                 public void onItemSelected(AdapterView<?> arg0, View arg1,  
  155.                         int position, long arg3)  
  156.                 {  
  157.                     city_str = citys.get(position);  
  158.                 }  
  159.   
  160.                 @Override  
  161.                 public void onNothingSelected(AdapterView<?> arg0)  
  162.                 {  
  163.   
  164.                 }  
  165.             });  
  166.   
  167.             // 选择城市对话框   
  168.             AlertDialog.Builder dialog = new AlertDialog.Builder(this);  
  169.             dialog.setTitle("请选择所属城市");  
  170.             dialog.setView(view);  
  171.             dialog.setPositiveButton("确定",  
  172.                     new DialogInterface.OnClickListener()  
  173.                     {  
  174.   
  175.                         @Override  
  176.                         public void onClick(DialogInterface dialog, int which)  
  177.                         {  
  178.                             city_text.setText(city_str);  
  179.                             writeSharpPreference(city_str);  
  180.                             refresh(city_str);  
  181.   
  182.                         }  
  183.                     });  
  184.             dialog.setNegativeButton("取消",  
  185.                     new DialogInterface.OnClickListener()  
  186.                     {  
  187.   
  188.                         @Override  
  189.                         public void onClick(DialogInterface dialog, int which)  
  190.                         {  
  191.                             dialog.dismiss();  
  192.   
  193.                         }  
  194.                     });  
  195.   
  196.             dialog.show();  
  197.   
  198.             break;  
  199.   
  200.         default:  
  201.             break;  
  202.         }  
  203.   
  204.     }  
  205.   
  206.     protected void refresh(String city_str)  
  207.     {  
  208.         SoapObject detail = WebServiceUtil.getWeatherByCity(city_str);  
  209.   
  210.         try  
  211.         {  
  212.             // 取得<string>10月13日 中雨转小雨</string>中的数据   
  213.             String date = detail.getProperty(7).toString();  
  214.             // 将"10月13日 中雨转小雨"拆分成两个数组   
  215.             String[] date_array = date.split(" ");  
  216.             TextView today_text = (TextView) findViewById(R.id.today);  
  217.             today_text.setText(date_array[0]);  
  218.   
  219.             // 取得<string>江苏 无锡</string>中的数据   
  220.             TextView city_text = (TextView) findViewById(R.id.city_text);  
  221.             city_text.setText(detail.getProperty(1).toString());  
  222.   
  223.             TextView today_weather = (TextView) findViewById(R.id.today_weather);  
  224.             today_weather.setText(date_array[1]);  
  225.   
  226.             // 取得<string>15℃/21℃</string>中的数据   
  227.             TextView qiweng_text = (TextView) findViewById(R.id.qiweng);  
  228.             qiweng_text.setText(detail.getProperty(8).toString());  
  229.   
  230.             // 取得<string>今日天气实况:气温:20℃;风向/风力:东南风   
  231.             // 2级;湿度:79%</string>中的数据,并通过":"拆分成数组   
  232.             TextView shidu_text = (TextView) findViewById(R.id.shidu);  
  233.             String date1 = detail.getProperty(4).toString();  
  234.             shidu_text.setText(date1.split(":")[4]);  
  235.   
  236.             // 取得<string>东北风3-4级</string>中的数据   
  237.             TextView fengli_text = (TextView) findViewById(R.id.fengli);  
  238.             fengli_text.setText(detail.getProperty(9).toString());  
  239.   
  240.             // 取得<string>空气质量:良;紫外线强度:最弱</string>中的数据,并通过";"拆分,再通过":"拆分,拆分两次,取得我们需要的数据   
  241.             String date2 = detail.getProperty(5).toString();  
  242.             String[] date2_array = date2.split(";");  
  243.             TextView kongqi_text = (TextView) findViewById(R.id.kongqi);  
  244.             kongqi_text.setText(date2_array[0].split(":")[1]);  
  245.   
  246.             TextView zhiwai_text = (TextView) findViewById(R.id.zhiwai);  
  247.             zhiwai_text.setText(date2_array[1].split(":")[1]);  
  248.   
  249.             // 设置小贴士数据   
  250.             // <string>穿衣指数:较凉爽,建议着长袖衬衫加单裤等春秋过渡装。年老体弱者宜着针织长袖衬衫、马甲和长裤。感冒指数:虽然温度适宜但风力较大,仍较易发生感冒,体质较弱的朋友请注意适当防护。   
  251.             //运动指数:阴天,较适宜开展各种户内外运动。洗车指数:较不宜洗车,路面少量积水,如果执意擦洗汽车,要做好溅上泥水的心理准备。晾晒指数:天气阴沉,不利于水分的迅速蒸发,不太适宜晾晒。若需要晾晒,请尽量选择通风的地点。   
  252.             //旅游指数:阴天,风稍大,但温度适宜,总体来说还是好天气。这样的天气很适宜旅游,您可以尽情享受大自然的风光。路况指数:阴天,路面比较干燥,路况较好。舒适度指数:温度适宜,风力不大,您在这样的天气条件下,会感到比较清爽和舒适。   
  253.             //空气污染指数:气象条件有利于空气污染物稀释、扩散和清除,可在室外正常活动。紫外线指数:属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。</string>   
  254.             String[] xiaotieshi = detail.getProperty(6).toString().split("\n");  
  255.             TextView xiaotieshi_text = (TextView) findViewById(R.id.xiaotieshi);  
  256.             xiaotieshi_text.setText(xiaotieshi[0]);  
  257.   
  258.             // 设置当日图片   
  259.             ImageView image = (ImageView) findViewById(R.id.imageView1);  
  260.             int icon = parseIcon(detail.getProperty(10).toString());  
  261.             image.setImageResource(icon);  
  262.   
  263.             // 取得第二天的天气情况   
  264.             String[] date_str = detail.getProperty(12).toString().split(" ");  
  265.             TextView tomorrow_date = (TextView) findViewById(R.id.tomorrow_date);  
  266.             tomorrow_date.setText(date_str[0]);  
  267.   
  268.             TextView tomorrow_qiweng = (TextView) findViewById(R.id.tomorrow_qiweng);  
  269.             tomorrow_qiweng.setText(detail.getProperty(13).toString());  
  270.   
  271.             TextView tomorrow_tianqi = (TextView) findViewById(R.id.tomorrow_tianqi);  
  272.             tomorrow_tianqi.setText(date_str[1]);  
  273.   
  274.             ImageView tomorrow_image = (ImageView) findViewById(R.id.tomorrow_image);  
  275.             int icon1 = parseIcon(detail.getProperty(15).toString());  
  276.             tomorrow_image.setImageResource(icon1);  
  277.   
  278.             // 取得第三天的天气情况   
  279.             String[] date_str1 = detail.getProperty(17).toString().split(" ");  
  280.             TextView afterday_date = (TextView) findViewById(R.id.afterday_date);  
  281.             afterday_date.setText(date_str1[0]);  
  282.   
  283.             TextView afterday_qiweng = (TextView) findViewById(R.id.afterday_qiweng);  
  284.             afterday_qiweng.setText(detail.getProperty(18).toString());  
  285.   
  286.             TextView afterday_tianqi = (TextView) findViewById(R.id.afterday_tianqi);  
  287.             afterday_tianqi.setText(date_str1[1]);  
  288.   
  289.             ImageView afterday_image = (ImageView) findViewById(R.id.afterday_image);  
  290.             int icon2 = parseIcon(detail.getProperty(20).toString());  
  291.             afterday_image.setImageResource(icon2);  
  292.   
  293.             // 取得第四天的天气情况   
  294.             String[] date_str3 = detail.getProperty(22).toString().split(" ");  
  295.             TextView nextday_date = (TextView) findViewById(R.id.nextday_date);  
  296.             nextday_date.setText(date_str3[0]);  
  297.   
  298.             TextView nextday_qiweng = (TextView) findViewById(R.id.nextday_qiweng);  
  299.             nextday_qiweng.setText(detail.getProperty(23).toString());  
  300.   
  301.             TextView nextday_tianqi = (TextView) findViewById(R.id.nextday_tianqi);  
  302.             nextday_tianqi.setText(date_str3[1]);  
  303.   
  304.             ImageView nextday_image = (ImageView) findViewById(R.id.nextday_image);  
  305.             int icon3 = parseIcon(detail.getProperty(25).toString());  
  306.             nextday_image.setImageResource(icon3);  
  307.   
  308.         } catch (Exception e)  
  309.         {  
  310.             showTast(detail.getProperty(0).toString().split("。")[0]);  
  311.         }  
  312.   
  313.     }  
  314.   
  315.     // 工具方法,该方法负责把返回的天气图标字符串,转换为程序的图片资源ID。   
  316.     private int parseIcon(String strIcon)  
  317.     {  
  318.         if (strIcon == null)  
  319.             return -1;  
  320.         if ("0.gif".equals(strIcon))  
  321.             return R.drawable.a_0;  
  322.         if ("1.gif".equals(strIcon))  
  323.             return R.drawable.a_1;  
  324.         if ("2.gif".equals(strIcon))  
  325.             return R.drawable.a_2;  
  326.         if ("3.gif".equals(strIcon))  
  327.             return R.drawable.a_3;  
  328.         if ("4.gif".equals(strIcon))  
  329.             return R.drawable.a_4;  
  330.         if ("5.gif".equals(strIcon))  
  331.             return R.drawable.a_5;  
  332.         if ("6.gif".equals(strIcon))  
  333.             return R.drawable.a_6;  
  334.         if ("7.gif".equals(strIcon))  
  335.             return R.drawable.a_7;  
  336.         if ("8.gif".equals(strIcon))  
  337.             return R.drawable.a_8;  
  338.         if ("9.gif".equals(strIcon))  
  339.             return R.drawable.a_9;  
  340.         if ("10.gif".equals(strIcon))  
  341.             return R.drawable.a_10;  
  342.         if ("11.gif".equals(strIcon))  
  343.             return R.drawable.a_11;  
  344.         if ("12.gif".equals(strIcon))  
  345.             return R.drawable.a_12;  
  346.         if ("13.gif".equals(strIcon))  
  347.             return R.drawable.a_13;  
  348.         if ("14.gif".equals(strIcon))  
  349.             return R.drawable.a_14;  
  350.         if ("15.gif".equals(strIcon))  
  351.             return R.drawable.a_15;  
  352.         if ("16.gif".equals(strIcon))  
  353.             return R.drawable.a_16;  
  354.         if ("17.gif".equals(strIcon))  
  355.             return R.drawable.a_17;  
  356.         if ("18.gif".equals(strIcon))  
  357.             return R.drawable.a_18;  
  358.         if ("19.gif".equals(strIcon))  
  359.             return R.drawable.a_19;  
  360.         if ("20.gif".equals(strIcon))  
  361.             return R.drawable.a_20;  
  362.         if ("21.gif".equals(strIcon))  
  363.             return R.drawable.a_21;  
  364.         if ("22.gif".equals(strIcon))  
  365.             return R.drawable.a_22;  
  366.         if ("23.gif".equals(strIcon))  
  367.             return R.drawable.a_23;  
  368.         if ("24.gif".equals(strIcon))  
  369.             return R.drawable.a_24;  
  370.         if ("25.gif".equals(strIcon))  
  371.             return R.drawable.a_25;  
  372.         if ("26.gif".equals(strIcon))  
  373.             return R.drawable.a_26;  
  374.         if ("27.gif".equals(strIcon))  
  375.             return R.drawable.a_27;  
  376.         if ("28.gif".equals(strIcon))  
  377.             return R.drawable.a_28;  
  378.         if ("29.gif".equals(strIcon))  
  379.             return R.drawable.a_29;  
  380.         if ("30.gif".equals(strIcon))  
  381.             return R.drawable.a_30;  
  382.         if ("31.gif".equals(strIcon))  
  383.             return R.drawable.a_31;  
  384.         return 0;  
  385.     }  
  386.       
  387.       
  388.     public void writeSharpPreference(String string){  
  389.           
  390.         SharedPreferences.Editor editor = preference.edit();  
  391.         editor.putString("city", string);  
  392.         editor.commit();  
  393.       
  394.     }  
  395.       
  396.     public String readSharpPreference(){  
  397.           
  398.         String city = preference.getString("city""无锡");  
  399.           
  400.         return city;  
  401.           
  402.     }  
  403. }  
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.kang.net.WebServiceUtil;

public class WeatherWebServiceActivity extends Activity
{
	private TextView text;
	private Button city_btn;
	private static final int CITY = 0x11;
	private String city_str;
	private TextView city_text;
	private Spinner province_spinner;
	private Spinner city_spinner;
	private List<String> provinces;
	private List<String> citys;
	private SharedPreferences preference;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏

		setContentView(R.layout.main);
		
		preference = getSharedPreferences("weather", MODE_PRIVATE);
		city_str = readSharpPreference();

		city_text = (TextView) findViewById(R.id.city);
		city_text.setText(city_str);

		text = (TextView) findViewById(R.id.test);

		city_btn = (Button) findViewById(R.id.city_button);

		city_btn.setOnClickListener(new ClickEvent());

		findViewById(R.id.content_today_layout).getBackground().setAlpha(120);
		findViewById(R.id.content_small_bg1).getBackground().setAlpha(120);
		findViewById(R.id.content_small_bg2).getBackground().setAlpha(120);
		findViewById(R.id.content_small_bg3).getBackground().setAlpha(120);
		
		refresh(city_str);

	}

	class ClickEvent implements View.OnClickListener
	{

		@Override
		public void onClick(View v)
		{
			switch (v.getId())
			{
			case R.id.city_button:

				show_dialog(CITY);

				break;

			default:
				break;
			}

		}

	}

	public void showTast(String string)
	{
		Toast.makeText(WeatherWebServiceActivity.this, string, 1).show();

	}

	public void show_dialog(int cityId)
	{

		switch (cityId)
		{
		case CITY:

			// 取得city_layout.xml中的视图
			final View view = LayoutInflater.from(this).inflate(
					R.layout.city_layout, null);

			// 省份Spinner
			province_spinner = (Spinner) view
					.findViewById(R.id.province_spinner);
			// 城市Spinner
			city_spinner = (Spinner) view.findViewById(R.id.city_spinner);

			// 省份列表
			provinces = WebServiceUtil.getProvinceList();

			ArrayAdapter adapter = new ArrayAdapter(this,
					android.R.layout.simple_spinner_item, provinces);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

			province_spinner.setAdapter(adapter);
			// 省份Spinner监听器
			province_spinner
					.setOnItemSelectedListener(new OnItemSelectedListener()
					{

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int position, long arg3)
						{

							citys = WebServiceUtil
									.getCityListByProvince(provinces
											.get(position));
							ArrayAdapter adapter1 = new ArrayAdapter(
									WeatherWebServiceActivity.this,
									android.R.layout.simple_spinner_item, citys);
							adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							city_spinner.setAdapter(adapter1);

						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0)
						{

						}
					});

			// 城市Spinner监听器
			city_spinner.setOnItemSelectedListener(new OnItemSelectedListener()
			{

				@Override
				public void onItemSelected(AdapterView<?> arg0, View arg1,
						int position, long arg3)
				{
					city_str = citys.get(position);
				}

				@Override
				public void onNothingSelected(AdapterView<?> arg0)
				{

				}
			});

			// 选择城市对话框
			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
			dialog.setTitle("请选择所属城市");
			dialog.setView(view);
			dialog.setPositiveButton("确定",
					new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							city_text.setText(city_str);
							writeSharpPreference(city_str);
							refresh(city_str);

						}
					});
			dialog.setNegativeButton("取消",
					new DialogInterface.OnClickListener()
					{

						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							dialog.dismiss();

						}
					});

			dialog.show();

			break;

		default:
			break;
		}

	}

	protected void refresh(String city_str)
	{
		SoapObject detail = WebServiceUtil.getWeatherByCity(city_str);

		try
		{
			// 取得<string>10月13日 中雨转小雨</string>中的数据
			String date = detail.getProperty(7).toString();
			// 将"10月13日 中雨转小雨"拆分成两个数组
			String[] date_array = date.split(" ");
			TextView today_text = (TextView) findViewById(R.id.today);
			today_text.setText(date_array[0]);

			// 取得<string>江苏 无锡</string>中的数据
			TextView city_text = (TextView) findViewById(R.id.city_text);
			city_text.setText(detail.getProperty(1).toString());

			TextView today_weather = (TextView) findViewById(R.id.today_weather);
			today_weather.setText(date_array[1]);

			// 取得<string>15℃/21℃</string>中的数据
			TextView qiweng_text = (TextView) findViewById(R.id.qiweng);
			qiweng_text.setText(detail.getProperty(8).toString());

			// 取得<string>今日天气实况:气温:20℃;风向/风力:东南风
			// 2级;湿度:79%</string>中的数据,并通过":"拆分成数组
			TextView shidu_text = (TextView) findViewById(R.id.shidu);
			String date1 = detail.getProperty(4).toString();
			shidu_text.setText(date1.split(":")[4]);

			// 取得<string>东北风3-4级</string>中的数据
			TextView fengli_text = (TextView) findViewById(R.id.fengli);
			fengli_text.setText(detail.getProperty(9).toString());

			// 取得<string>空气质量:良;紫外线强度:最弱</string>中的数据,并通过";"拆分,再通过":"拆分,拆分两次,取得我们需要的数据
			String date2 = detail.getProperty(5).toString();
			String[] date2_array = date2.split(";");
			TextView kongqi_text = (TextView) findViewById(R.id.kongqi);
			kongqi_text.setText(date2_array[0].split(":")[1]);

			TextView zhiwai_text = (TextView) findViewById(R.id.zhiwai);
			zhiwai_text.setText(date2_array[1].split(":")[1]);

			// 设置小贴士数据
			// <string>穿衣指数:较凉爽,建议着长袖衬衫加单裤等春秋过渡装。年老体弱者宜着针织长袖衬衫、马甲和长裤。感冒指数:虽然温度适宜但风力较大,仍较易发生感冒,体质较弱的朋友请注意适当防护。
			//运动指数:阴天,较适宜开展各种户内外运动。洗车指数:较不宜洗车,路面少量积水,如果执意擦洗汽车,要做好溅上泥水的心理准备。晾晒指数:天气阴沉,不利于水分的迅速蒸发,不太适宜晾晒。若需要晾晒,请尽量选择通风的地点。
			//旅游指数:阴天,风稍大,但温度适宜,总体来说还是好天气。这样的天气很适宜旅游,您可以尽情享受大自然的风光。路况指数:阴天,路面比较干燥,路况较好。舒适度指数:温度适宜,风力不大,您在这样的天气条件下,会感到比较清爽和舒适。
			//空气污染指数:气象条件有利于空气污染物稀释、扩散和清除,可在室外正常活动。紫外线指数:属弱紫外线辐射天气,无需特别防护。若长期在户外,建议涂擦SPF在8-12之间的防晒护肤品。</string>
			String[] xiaotieshi = detail.getProperty(6).toString().split("\n");
			TextView xiaotieshi_text = (TextView) findViewById(R.id.xiaotieshi);
			xiaotieshi_text.setText(xiaotieshi[0]);

			// 设置当日图片
			ImageView image = (ImageView) findViewById(R.id.imageView1);
			int icon = parseIcon(detail.getProperty(10).toString());
			image.setImageResource(icon);

			// 取得第二天的天气情况
			String[] date_str = detail.getProperty(12).toString().split(" ");
			TextView tomorrow_date = (TextView) findViewById(R.id.tomorrow_date);
			tomorrow_date.setText(date_str[0]);

			TextView tomorrow_qiweng = (TextView) findViewById(R.id.tomorrow_qiweng);
			tomorrow_qiweng.setText(detail.getProperty(13).toString());

			TextView tomorrow_tianqi = (TextView) findViewById(R.id.tomorrow_tianqi);
			tomorrow_tianqi.setText(date_str[1]);

			ImageView tomorrow_image = (ImageView) findViewById(R.id.tomorrow_image);
			int icon1 = parseIcon(detail.getProperty(15).toString());
			tomorrow_image.setImageResource(icon1);

			// 取得第三天的天气情况
			String[] date_str1 = detail.getProperty(17).toString().split(" ");
			TextView afterday_date = (TextView) findViewById(R.id.afterday_date);
			afterday_date.setText(date_str1[0]);

			TextView afterday_qiweng = (TextView) findViewById(R.id.afterday_qiweng);
			afterday_qiweng.setText(detail.getProperty(18).toString());

			TextView afterday_tianqi = (TextView) findViewById(R.id.afterday_tianqi);
			afterday_tianqi.setText(date_str1[1]);

			ImageView afterday_image = (ImageView) findViewById(R.id.afterday_image);
			int icon2 = parseIcon(detail.getProperty(20).toString());
			afterday_image.setImageResource(icon2);

			// 取得第四天的天气情况
			String[] date_str3 = detail.getProperty(22).toString().split(" ");
			TextView nextday_date = (TextView) findViewById(R.id.nextday_date);
			nextday_date.setText(date_str3[0]);

			TextView nextday_qiweng = (TextView) findViewById(R.id.nextday_qiweng);
			nextday_qiweng.setText(detail.getProperty(23).toString());

			TextView nextday_tianqi = (TextView) findViewById(R.id.nextday_tianqi);
			nextday_tianqi.setText(date_str3[1]);

			ImageView nextday_image = (ImageView) findViewById(R.id.nextday_image);
			int icon3 = parseIcon(detail.getProperty(25).toString());
			nextday_image.setImageResource(icon3);

		} catch (Exception e)
		{
			showTast(detail.getProperty(0).toString().split("。")[0]);
		}

	}

	// 工具方法,该方法负责把返回的天气图标字符串,转换为程序的图片资源ID。
	private int parseIcon(String strIcon)
	{
		if (strIcon == null)
			return -1;
		if ("0.gif".equals(strIcon))
			return R.drawable.a_0;
		if ("1.gif".equals(strIcon))
			return R.drawable.a_1;
		if ("2.gif".equals(strIcon))
			return R.drawable.a_2;
		if ("3.gif".equals(strIcon))
			return R.drawable.a_3;
		if ("4.gif".equals(strIcon))
			return R.drawable.a_4;
		if ("5.gif".equals(strIcon))
			return R.drawable.a_5;
		if ("6.gif".equals(strIcon))
			return R.drawable.a_6;
		if ("7.gif".equals(strIcon))
			return R.drawable.a_7;
		if ("8.gif".equals(strIcon))
			return R.drawable.a_8;
		if ("9.gif".equals(strIcon))
			return R.drawable.a_9;
		if ("10.gif".equals(strIcon))
			return R.drawable.a_10;
		if ("11.gif".equals(strIcon))
			return R.drawable.a_11;
		if ("12.gif".equals(strIcon))
			return R.drawable.a_12;
		if ("13.gif".equals(strIcon))
			return R.drawable.a_13;
		if ("14.gif".equals(strIcon))
			return R.drawable.a_14;
		if ("15.gif".equals(strIcon))
			return R.drawable.a_15;
		if ("16.gif".equals(strIcon))
			return R.drawable.a_16;
		if ("17.gif".equals(strIcon))
			return R.drawable.a_17;
		if ("18.gif".equals(strIcon))
			return R.drawable.a_18;
		if ("19.gif".equals(strIcon))
			return R.drawable.a_19;
		if ("20.gif".equals(strIcon))
			return R.drawable.a_20;
		if ("21.gif".equals(strIcon))
			return R.drawable.a_21;
		if ("22.gif".equals(strIcon))
			return R.drawable.a_22;
		if ("23.gif".equals(strIcon))
			return R.drawable.a_23;
		if ("24.gif".equals(strIcon))
			return R.drawable.a_24;
		if ("25.gif".equals(strIcon))
			return R.drawable.a_25;
		if ("26.gif".equals(strIcon))
			return R.drawable.a_26;
		if ("27.gif".equals(strIcon))
			return R.drawable.a_27;
		if ("28.gif".equals(strIcon))
			return R.drawable.a_28;
		if ("29.gif".equals(strIcon))
			return R.drawable.a_29;
		if ("30.gif".equals(strIcon))
			return R.drawable.a_30;
		if ("31.gif".equals(strIcon))
			return R.drawable.a_31;
		return 0;
	}
	
	
	public void writeSharpPreference(String string){
		
		SharedPreferences.Editor editor = preference.edit();
		editor.putString("city", string);
		editor.commit();
	
	}
	
	public String readSharpPreference(){
		
		String city = preference.getString("city", "无锡");
		
		return city;
		
	}
}

 这里面也只是一些数据有整理和汇总,主要是希望读者能够学习如何使用Ksoap2这个类,代码里的注释也写的很清楚了.其实如果想做出好的应用的话就应该学会如何利用网络资源来跟自己的应用交互,毕竟网络资源是无穷的,像XML解析之类的,你也可以解析团购网站的XML文件,呵呵,下一个项目就解析XML文件了,呵呵,这里就说到这里吧

源码下载:Android天气预报 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值