這個項目是基於webservice的,用ksoap2來解析網路上的WebService的,我們先看做出的
其實也沒有很多技術難題,我們直接來看源碼再做說明吧
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提供服務的URLstatic 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 ServicehttpTranstation.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 ServicehttpTranstation.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 ServicehttpTranstation.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中的代碼:
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. */@Overridepublic 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{@Overridepublic 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);// 省份Spinnerprovince_spinner = (Spinner) view.findViewById(R.id.province_spinner);// 城市Spinnercity_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(){@Overridepublic 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);}@Overridepublic void onNothingSelected(AdapterView<?> arg0){}});// 城市Spinner監聽器city_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3){city_str = citys.get(position);}@Overridepublic void onNothingSelected(AdapterView<?> arg0){}});// 選擇城市對話方塊AlertDialog.Builder dialog = new AlertDialog.Builder(this);dialog.setTitle("請選擇所屬城市");dialog.setView(view);dialog.setPositiveButton("確定",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){city_text.setText(city_str);writeSharpPreference(city_str);refresh(city_str);}});dialog.setNegativeButton("取消",new DialogInterface.OnClickListener(){@Overridepublic 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天氣預報