利用WebService解析出的天氣預報

來源:互聯網
上載者:User

事先聲明,這個代碼是《瘋狂android講義》上的,我只不過動手打了一遍,有些地方是拷貝的

布局檔案

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content"    android:orientation="vertical" >    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="@string/province" />        <!-- 讓使用者選擇省份的Spinner -->        <Spinner            android:id="@+id/province"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />    </LinearLayout>    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <TextView            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:hint="@string/city" />        <!-- 讓使用者選擇城市的Spinner -->        <Spinner            android:id="@+id/city"            android:layout_width="fill_parent"            android:layout_height="wrap_content" />    </LinearLayout>    <!-- 顯示今天天氣的圖片和文字框 -->    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <ImageView            android:id="@+id/todayWhIcon1"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/todayWhIcon2"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <TextView            android:id="@+id/weatherToday"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_weight="1" />    </LinearLayout>    <!-- 顯示明天天氣的圖片和文字框 -->    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <ImageView            android:id="@+id/tomorrowWhIcon1"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/tomorrowWhIcon2"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <TextView            android:id="@+id/weatherTomorrow"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_weight="1" />    </LinearLayout>    <!-- 顯示後天天氣的圖片和文字框 -->    <LinearLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <ImageView            android:id="@+id/afterdayWhIcon1"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <ImageView            android:id="@+id/afterdayWhIcon2"            android:layout_width="wrap_content"            android:layout_height="wrap_content" />        <TextView            android:id="@+id/weatherAfterday"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:layout_weight="1" />    </LinearLayout>    <TextView        android:id="@+id/weatherCurrent"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>

主要activity檔案

package com.example.weatherservicedemo;import java.util.List;import org.ksoap2.serialization.SoapObject;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ImageView;import android.widget.Spinner;import android.widget.TextView;/** * Description: <br/> * site: <a href="http://www.crazyit.org">crazyit.org</a> <br/> * Copyright (C), 2001-2012, Yeeku.H.Lee <br/> * This program is protected by copyright laws. <br/> * Program Name: <br/> * Date: *  * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */public class MyWeather extends Activity {private Spinner provinceSpinner;private Spinner citySpinner;private ImageView todayWhIcon1;private ImageView todayWhIcon2;private TextView textWeatherToday;private ImageView tomorrowWhIcon1;private ImageView tomorrowWhIcon2;private TextView textWeatherTomorrow;private ImageView afterdayWhIcon1;private ImageView afterdayWhIcon2;private TextView textWeatherAfterday;private TextView textWeatherCurrent;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);todayWhIcon1 = (ImageView) findViewById(R.id.todayWhIcon1);todayWhIcon2 = (ImageView) findViewById(R.id.todayWhIcon2);textWeatherToday = (TextView) findViewById(R.id.weatherToday);tomorrowWhIcon1 = (ImageView) findViewById(R.id.tomorrowWhIcon1);tomorrowWhIcon2 = (ImageView) findViewById(R.id.tomorrowWhIcon2);textWeatherTomorrow = (TextView) findViewById(R.id.weatherTomorrow);afterdayWhIcon1 = (ImageView) findViewById(R.id.afterdayWhIcon1);afterdayWhIcon2 = (ImageView) findViewById(R.id.afterdayWhIcon2);textWeatherAfterday = (TextView) findViewById(R.id.weatherAfterday);textWeatherCurrent = (TextView) findViewById(R.id.weatherCurrent);// 擷取程式介面中選擇省份、城市的Spinner組件provinceSpinner = (Spinner) findViewById(R.id.province);citySpinner = (Spinner) findViewById(R.id.city);// 調用遠程Web Service擷取省份列表List<String> provinces = WebServiceUtil.getProvinceList();ListAdapter adapter = new ListAdapter(this, provinces);// 使用Spinner顯示省份列表provinceSpinner.setAdapter(adapter);// 當省份Spinner的選擇項被改變時provinceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {public void onItemSelected(AdapterView<?> source, View parent,int position, long id) {List<String> cities = WebServiceUtil.getCityListByProvince(provinceSpinner.getSelectedItem().toString());ListAdapter cityAdapter = new ListAdapter(MyWeather.this,cities);// 使用Spinner顯示城市列表citySpinner.setAdapter(cityAdapter);}public void onNothingSelected(AdapterView<?> arg0) {}});// 當城市Spinner的選擇項被改變時citySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {public void onItemSelected(AdapterView<?> source, View parent,int position, long id) {showWeather(citySpinner.getSelectedItem().toString());}public void onNothingSelected(AdapterView<?> arg0) {}});}private void showWeather(String city) {String weatherToday = null;String weatherTomorrow = null;String weatherAfterday = null;String weatherCurrent = null;int iconToday[] = new int[2];int iconTomorrow[] = new int[2];int iconAfterday[] = new int[2];// 擷取遠程Web Service返回的對象SoapObject detail = WebServiceUtil.getWeatherByCity(city);// 擷取天氣實況weatherCurrent = detail.getProperty(4).toString();// 解析今天的天氣情況String date = detail.getProperty(7).toString();weatherToday = "今天:" + date.split(" ")[0];weatherToday = weatherToday + "\n天氣:" + date.split(" ")[1];weatherToday = weatherToday + "\n氣溫:"+ detail.getProperty(8).toString();weatherToday = weatherToday + "\n風力:"+ detail.getProperty(9).toString() + "\n";iconToday[0] = parseIcon(detail.getProperty(10).toString());iconToday[1] = parseIcon(detail.getProperty(11).toString());// 解析明天的天氣情況date = detail.getProperty(12).toString();weatherTomorrow = "明天:" + date.split(" ")[0];weatherTomorrow = weatherTomorrow + "\n天氣:" + date.split(" ")[1];weatherTomorrow = weatherTomorrow + "\n氣溫:"+ detail.getProperty(13).toString();weatherTomorrow = weatherTomorrow + "\n風力:"+ detail.getProperty(14).toString() + "\n";iconTomorrow[0] = parseIcon(detail.getProperty(15).toString());iconTomorrow[1] = parseIcon(detail.getProperty(16).toString());// 解析後天的天氣情況date = detail.getProperty(17).toString();weatherAfterday = "後天:" + date.split(" ")[0];weatherAfterday = weatherAfterday + "\n天氣:" + date.split(" ")[1];weatherAfterday = weatherAfterday + "\n氣溫:"+ detail.getProperty(18).toString();weatherAfterday = weatherAfterday + "\n風力:"+ detail.getProperty(19).toString() + "\n";iconAfterday[0] = parseIcon(detail.getProperty(20).toString());iconAfterday[1] = parseIcon(detail.getProperty(21).toString());// 更新當天的天氣實況textWeatherCurrent.setText(weatherCurrent);// 更新顯示今天天氣的表徵圖和文字框textWeatherToday.setText(weatherToday);todayWhIcon1.setImageResource(iconToday[0]);todayWhIcon2.setImageResource(iconToday[1]);// 更新顯示明天天氣的表徵圖和文字框textWeatherTomorrow.setText(weatherTomorrow);tomorrowWhIcon1.setImageResource(iconTomorrow[0]);tomorrowWhIcon2.setImageResource(iconTomorrow[1]);// 更新顯示後天天氣的表徵圖和文字框textWeatherAfterday.setText(weatherAfterday);afterdayWhIcon1.setImageResource(iconAfterday[0]);afterdayWhIcon2.setImageResource(iconAfterday[1]);}// 工具方法,該方法負責把返回的天氣表徵圖字串,轉換為程式的圖片資源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;}}

協助檔案

package com.example.weatherservicedemo;import java.io.IOException;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;import org.xmlpull.v1.XmlPullParserException;/** * Description: <br/> * 網站: <a href="http://www.crazyit.org">瘋狂Java聯盟</a> <br/> * Copyright (C), 2001-2012, Yeeku.H.Lee <br/> * This program is protected by copyright laws. <br/> * Program Name: <br/> * Date: *  * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */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";// 調用遠程Web Service擷取省份列表public static List<String> getProvinceList() {// 調用的方法String methodName = "getRegionProvince";// 建立HttpTransportSE傳輸對象HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.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 Serviceht.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 (IOException e) {e.printStackTrace();} catch (XmlPullParserException e) {e.printStackTrace();}return null;}// 根據省份擷取城市列表public static List<String> getCityListByProvince(String province) {// 調用的方法String methodName = "getSupportCityString";// 建立HttpTransportSE傳輸對象HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.debug = true;// 執行個體化SoapObject對象SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);// 添加一個請求參數soapObject.addProperty("theRegionCode", province);// 使用SOAP1.1協議建立Envelop對象SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.bodyOut = soapObject;// 設定與.Net提供的Web Service保持較好的相容性envelope.dotNet = true;try {// 調用Web Serviceht.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 (IOException e) {e.printStackTrace();} catch (XmlPullParserException 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++) {// 解析出每個省份result.add(detail.getProperty(i).toString().split(",")[0]);}return result;}public static SoapObject getWeatherByCity(String cityName) {String methodName = "getWeather";HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.debug = true;SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);soapObject.addProperty("theCityCode", cityName);envelope.bodyOut = soapObject;// 設定與.Net提供的Web Service保持較好的相容性envelope.dotNet = true;try {ht.call(SERVICE_NS + methodName, envelope);SoapObject result = (SoapObject) envelope.bodyIn;SoapObject detail = (SoapObject) result.getProperty(methodName+ "Result");return detail;} catch (Exception e) {e.printStackTrace();}return null;}}

適配器檔案

package com.example.weatherservicedemo;import java.util.List;import android.content.Context;import android.graphics.Color;import android.view.View;import android.view.ViewGroup;import android.widget.BaseAdapter;import android.widget.TextView;/** * Description: <br/> * 網站: <a href="http://www.crazyit.org">瘋狂Java聯盟</a> <br/> * Copyright (C), 2001-2012, Yeeku.H.Lee <br/> * This program is protected by copyright laws. <br/> * Program Name: <br/> * Date: *  * @author Yeeku.H.Lee kongyeeku@163.com * @version 1.0 */public class ListAdapter extends BaseAdapter {private Context context;private List<String> values;public ListAdapter(Context context, List<String> values) {this.context = context;this.values = values;}public int getCount() {return values.size();}public Object getItem(int position) {return values.get(position);}public long getItemId(int position) {return position;}public View getView(int position, View convertView, ViewGroup parent) {TextView text = new TextView(context);text.setText(values.get(position));text.setTextSize(20);text.setTextColor(Color.BLACK);return text;}}

還有訪問網路的許可權呀,事先說明一下,這個只有在wif下運行成功,移動網路運行失敗,不知道怎麼回事,有明白的,給哥們呢我留個言,大恩不言謝呀。

<manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.weatherservicedemo"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk android:minSdkVersion="8" />    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MyWeather"            android:label="@string/title_activity_main" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

後面我會把原始碼上傳,因為還有一個架包沒辦法貼出來。也可以百度搜尋一下,ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar架包

啟動並執行時候可能會有no class not found 的錯誤,說找不到那個類檔案,告訴你一個解決的辦法,如

也可以看這篇文章解決---http://blog.csdn.net/wang6279026/article/details/8098100

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.