今天学习《疯狂Android讲义》,看到web service的使用这章时,准备点时间,做个学习笔记,做一个天气预报的apk出来,顺便也巩固下sharedpreference 的用法

该文章中使用到 ksoap2-android-assembly-3.2.0-jar-with-dependencies.jar 在可以在网站 http://code.google.com/p/ksoap2-android/  下载

web service服务器地址 : http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx

使用 ksoap2-android调用web service的步骤:

1、创建HttpTransportSE对象,该对象用于调用Webservice操作。
HttpTransportSE ht = new HttpTransportSE(SERVICE_URL); 
其中:SERVICE_URL是webservice提供服务的url 本例中为:public static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";

2、使用SOAP1.1协议创建SoapSerializationEnvelope对象。
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
作用:使用SoapSerializationEnvelope对象的bodyOut属性传给服务器, 服务器响应生成的SOAP消息也通过SoapSerializationEnvelope对象的bodyin属性来获取

3、创建SoapObject对象,创建该对象时需要传入所要调用Web Service的命名空间。
SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);
说明:
第一个参数表示WebService的命名空间,可以从WSDL文档中找到WebService的命名空间。本例中:public static final String SERVICE_NS = "http://WebXml.com.cn/";
第二个参数表示要调用的WebService方法名。

4、调用方法 如果有参数需要传给Web Servcie服务端,则调用SoapObject对象的addProperty(String name,Object value)方法来设置参数,该方法的name参数指定参数名;value参数指定参数值。
//final String methodName = "getSupportCityString";
soapObject.addProperty("theRegionCode", province);

5、调用SoapSerializationEnvelope的setOutputSoapObject()方法,或者直接对bodyOut属性赋值,将前两步创建的SoapObject对象设为SoapSerializationEnvelpe的传出SOAP消息体。
envelope.bodyOut = soapObject;

6、调用对象的call()方法,并以SoapSerializationEnvelpe作为参数调用远程Web Servcie。
ht.call(SERVICE_NS + methodName, envelope);

7、调用完成后,访问SoapSerializationEnvelope对象的bodyIn属性,该属性返回一个SoapObjectd对象,该对象就代表了Web Service的返回消息。解析该SoapObject对象,即可获取调用Web Service的返回值。     
if(envelope.getResponse() != null){
//获取服务器响应返回的SOAP消息
SoapObject result = (SoapObject) envelope.bodyIn;
SoapObject detail = (SoapObject) result.getProperty(methodName+"Result");
//解析soap消息
return parseProvinceOrCity(detail);
}

附主要代码:WebServiceUtil.java

/*** 文件名:WebServiceUtil.java* author: jimbo* 版本信息 : magniwill copyright 2014* 日期:2014-4-11*  数据服务器地址   参考 : http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx*/
package cn.magniwill.weatherforecast.utils;import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;import android.database.CursorJoiner.Result;
import android.provider.ContactsContract.CommonDataKinds.Event;/*** @author Administrator**/
public class WebServiceUtil {// web services namespacepublic static final String SERVICE_NS = "http://WebXml.com.cn/";//web services 提供服务的urlpublic static final String SERVICE_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx";// 调用web services 取得省份列表public static List<String> getProvinceList(){List<String> province = new ArrayList<String>();//web service methodfinal String methodName = "getRegionProvince";//httptrafinal HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.debug = true;// 使用SOAP1.1协议创建envelop对象final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);// 实例化 SoapObject对象SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);envelope.bodyOut = soapObject;//设置于.net提供的web service保持好的兼容性envelope.dotNet = true;FutureTask<List<String>> task = new FutureTask<List<String>>(new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {//call web servicesht.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);}// TODO Auto-generated method stubreturn null;}});new Thread(task).start();try {return task.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}public static List<String> getCityListByProvince(String province){//method name final String methodName = "getSupportCityString";//创建HttpTransportSE传输对象final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.debug = true;//实例化SoapObject对象SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);//添加一个请求参数soapObject.addProperty("theRegionCode", province);// 使用SOAP1.1协议创建envelop对象final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.bodyOut = soapObject;//设置于.net提供的web service保持好的兼容性envelope.dotNet = true;FutureTask<List<String>> task = new FutureTask<List<String>>(new Callable<List<String>>() {@Overridepublic List<String> call() throws Exception {//call web servicesht.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);}// TODO Auto-generated method stubreturn null;}});new Thread(task).start();try {return task.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;     }public static SoapObject getWeatherByCity(String cityName){final String methodName = "getWeather";final HttpTransportSE ht = new HttpTransportSE(SERVICE_URL);ht.debug = true;final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);SoapObject soapObject = new SoapObject(SERVICE_NS, methodName);soapObject.addProperty("theCityCode", cityName);envelope.bodyOut = soapObject;//设置于.net提供的web service保持好的兼容性envelope.dotNet = true;FutureTask<SoapObject> task = new FutureTask<SoapObject>(new Callable<SoapObject>() {@Overridepublic SoapObject call() throws Exception {ht.call(SERVICE_NS + methodName, envelope);if(envelope.getResponse() != null){SoapObject result = (SoapObject) envelope.bodyIn;SoapObject detail = (SoapObject) result.getProperty(methodName+ "Result");// TODO Auto-generated method stubreturn detail;}return null;}});new Thread(task).start();try {return task.get();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;}/*** @param detail* @return*/private static List<String> parseProvinceOrCity(SoapObject detail) {List<String> result = new ArrayList<String>();for(int i=0; i<detail.getPropertyCount(); i++){// parse dataresult.add(detail.getProperty(i).toString().split(",")[0]);}// TODO Auto-generated method stubreturn result;}
}

MainActivity.java

package cn.magniwill.weatherforecast;import java.io.File;
import java.util.ArrayList;
import java.util.List;import org.ksoap2.serialization.SoapObject;import android.R.integer;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.magniwill.weatherforecast.utils.WebServiceUtil;public class MainActivity extends Activity {private Spinner mProvinceSpinner = null;private Spinner mCitySpinner = null;//today controlsprivate ImageView mTodayIV1 = null;private ImageView mTodayIV2 = null;private TextView mTodayTV = null;// tomorrow controlsprivate ImageView mTomorrowIV1 = null;private ImageView mTomorrowIV2 = null;private TextView mTomorrowTV = null;// afterday controlsprivate ImageView mAfterdayIV1 = null;private ImageView mAfterdayIV2 = null;private TextView mAfterdayTV = null;// the fourth day controlsprivate ImageView mFourthIV1 = null;private ImageView mFourthIV2 = null;private TextView mFourthTV = null;// the fifth day controlsprivate ImageView mFifthIV1 = null;private ImageView mFifthIV2 = null;private TextView mFifthTV = null;private static final String DEFAULT_PROVINCE = "上海";private static final String LASTSEL_PROVINCE = "last_secleted_province";private static final String LASTSEL_CITY = "last_secleted_city_";private static final String LASTSEL_FIRST_DAY_ICONS = "first_day_icons";private static final String LASTSEL_FIRST_DAY_WEATHER = "first_day_weather";private static final String LASTSEL_SECOND_DAY_ICONS = "second_day_icons";private static final String LASTSEL_SECOND_DAY_WEATHER = "second_day_weather";private static final String LASTSEL_THIRD_DAY_ICONS = "third_day_icons";private static final String LASTSEL_THIRD_DAY_WEATHER = "third_day_weather";private static final String LASTSEL_FOURTH_DAY_ICONS = "fourth_day_icons";private static final String LASTSEL_FOURTH_DAY_WEATHER = "fourth_day_weather";private static final String LASTSEL_FIFTH_DAY_ICONS = "fifth_day_icons";private static final String LASTSEL_FIFTH_DAY_WEATHER = "fifth_dday_weather";private static final String LASTSEL_SECOND_DAY = "last_secleted_city_";private static final String LASTSEL_THIERD_DAY = "last_secleted_city_";private static final String weather_setting = "settings";private static final String PROVINCE_KEY = "all_provinces";private SharedPreferences mPreference = null;//保存当前选择的省份名称private String mSelProvince = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// int controlsinitControls();// 判断是否能连上网络if(!canConnectInternet()){Toast.makeText(this, "Warring: Can't connect to internet!", Toast.LENGTH_SHORT).show();// finish();}List<String> provinces =  new ArrayList<String>();String savedProvinces = mPreference.getString(PROVINCE_KEY, null);if(savedProvinces != null){//读取保存省份列表String[] provinceArray = savedProvinces.trim().split(",");for(String str: provinceArray){provinces.add(str);}log("saved provinces is:"+provinces.toString() + "\nlength =" + provinceArray.length);}else{//第一次打开改程序,没有省份数据时  从服务器读取并保存provinces = WebServiceUtil.getProvinceList();if(provinces == null){log("WebServiceUtil.getProvinceList  == null");Toast.makeText(this, "未取得城市列表!", Toast.LENGTH_LONG).show();finish();return;}//保存省份数据StringBuilder provincesSB = new StringBuilder();for(int i=0; i<provinces.size(); i++){provincesSB.append(provinces.get(i));if(i != provinces.size()-1) {provincesSB.append(",");}}Editor editor = mPreference.edit();editor.putString(PROVINCE_KEY, provincesSB.toString());editor.commit();log("get provinces from internet :"+provinces.toString());}SpinnerAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, provinces);
//      SpinnerAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, provinces);mProvinceSpinner.setAdapter(adapter);int selPos = 0;String last_selected = mPreference.getString(LASTSEL_PROVINCE, DEFAULT_PROVINCE);for(String province: provinces){if(last_selected.equals(province)) break;selPos++;}mProvinceSpinner.setSelection(selPos);//province spinnermProvinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> source, View parent, int position, long id) {// TODO Auto-generated method stubmSelProvince = mProvinceSpinner.getSelectedItem().toString();log("select province :"+mSelProvince);List<String> cities = new ArrayList<String>();String savedCitys = mPreference.getString(mSelProvince, null);if(savedCitys != null){//读取保存的所选省份的城市列表String[] citiesArray = savedCitys.trim().split(",");for(String str: citiesArray){cities.add(str);}log("saved cities is:"+cities.toString() + "\nlength =" + citiesArray.length);}else{//第一次选择该省,没有城市数据时  从服务器读取并保存cities = WebServiceUtil.getCityListByProvince(mSelProvince);log("get cites from internet::"+cities.toString());}//保存城市列表数据StringBuilder citiesSB = new StringBuilder();for(int i=0; i<cities.size(); i++){citiesSB.append(cities.get(i));if(i != cities.size()-1) {citiesSB.append(",");}}// save LASTSEL_PROVINCEEditor editor = mPreference.edit();editor.putString(LASTSEL_PROVINCE, mSelProvince);//吧奥村城市列表editor.putString(mSelProvince, citiesSB.toString());editor.commit();// 显示 城市 spinnerif(cities == null){log("WebServiceUtil.getCityListByProvince("+mSelProvince+")"+ " == null");Toast.makeText(MainActivity.this, "未取得城市列表!", Toast.LENGTH_LONG).show();}else{SpinnerAdapter cityAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, cities);mCitySpinner.setAdapter(cityAdapter);//设置默认选择的城市为上次选择的 默认为:  第一个int selPos = 0;String last_selected_city = mPreference.getString(LASTSEL_CITY+mSelProvince, " ");for(String city: cities){if(last_selected_city.equals(city)) break;selPos++;}log("last_selected_city is:"+last_selected_city + " selPos="+selPos +" cities.size="+ cities.size());// 没有找到所选城市,默认为第一个selPos = selPos > cities.size() - 1 ? 0 : selPos;mCitySpinner.setSelection(selPos, true);}}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});     //city spinnermCitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {@Overridepublic void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {// TODO Auto-generated method stubString selCity = mCitySpinner.getSelectedItem().toString();log("selected city :"+selCity);//get city wathershowWeather(selCity);    //!!!!!!!!!!!!  main fun//保存最后选择的城市Editor editor = mPreference.edit();editor.putString(LASTSEL_CITY + mSelProvince, selCity);editor.commit();}@Overridepublic void onNothingSelected(AdapterView<?> arg0) {// TODO Auto-generated method stub}});}private boolean canConnectInternet() {boolean ret = false;//       final int WIFI = 1 ,CMWAP=2, CMNET = 3;ConnectivityManager conn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo info = conn.getActiveNetworkInfo();if(info != null){log(info.toString() + "----------- internet type:"+info.getType());ret = (info.getState() == NetworkInfo.State.CONNECTED);//            switch(info.getType()){
//          case ConnectivityManager.TYPE_WIFI:
//          case ConnectivityManager.TYPE_MOBILE:
//              ret = true;
//              break;
//
//          default:
//              break;
//          }}log("canConnectInternet = "+ ret);// TODO Auto-generated method stubreturn ret;}/*** @param selCity* * <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://WebXml.com.cn/"><string>直辖市 上海</string><string>闵行</string><string>2008</string><string>2014/04/12 16:44:23</string><string>今日天气实况:气温:18℃;风向/风力:西风 2级;湿度:90%</string><string>空气质量:暂无;紫外线强度:最弱</string><string>穿衣指数:较冷,建议着厚外套加毛衣等服装。 过敏指数:极易发,尽量减少外出,外出必须采取防护措施。 运动指数:较不宜,有较强降水,请在室内进行休闲运动。 洗车指数:不宜,有雨,雨水和泥水会弄脏爱车。 晾晒指数:不宜,有较强降水会淋湿衣物,不适宜晾晒。 旅游指数:暂无。 路况指数:湿滑,路面湿滑,车辆易打滑,减慢车速。 舒适度指数:舒适,白天不冷不热,风力不大。 空气污染指数:暂无。 紫外线指数:最弱,辐射弱,涂擦SPF8-12防晒护肤品。</string><string>4月12日 中雨转小雨</string>   //7<string>13℃/17℃</string><string>东南风4-5级转北风4-5级</string><string>8.gif</string>        <string>7.gif</string><string>4月13日 小雨转多云</string>  //12<string>12℃/19℃</string><string>北风4-5级转3-4级</string><string>7.gif</string><string>1.gif</string><string>4月14日 晴转多云</string> //17<string>11℃/21℃</string><string>东北风3-4级转东南风3-4级</string><string>0.gif</string><string>1.gif</string><string>4月15日 多云转小雨</string>    //22<string>13℃/22℃</string><string>东南风3-4级</string><string>1.gif</string><string>7.gif</string><string>4月16日 阴转小雨</string> //27<string>14℃/20℃</string><string>东南风4-5级</string><string>2.gif</string><string>7.gif</string></ArrayOfString>* */private final int WEATHER_ALLOC_MAX = 256;private void showWeather(String city) {//显示上次成功登陆保存的天气showLastWeather();// 获取远程web service返回的对象SoapObject detail = WebServiceUtil.getWeatherByCity(city);//获取天气实况if(detail == null){log("failed to getWeatherByCity("+city+")");return;}log("show weather of detial: "+detail);// 免费用户范文数量受限if(detail.toString().contains("发现错误")){//anyType{string=发现错误:免费用户24小时内访问超过规定数量。http://www.webxml.com.cn/; }//截取字串 : 免费用户24小时内访问超过规定数量。Toast.makeText(this, detail.toString().substring(20, 38), Toast.LENGTH_LONG).show();return;}log("show weather of "+detail.getProperty(0)+detail.getProperty(1)+detail.getProperty(2));//       String weatherCurrrent = detail.getProperty(4).toString(); //getProperty(4) : 德奥 <string>今日天气实况:气温。。。String weatherCurrrent = detail.getProperty(6).toString(); //getProperty(6) : 穿衣指数:较冷,。。。TextView weather = (TextView) findViewById(R.id.weather);weather.setText(getResources().getText(R.string.weather_advices)+weatherCurrrent);// weather memorybyte[] weatheBytes = new byte[WEATHER_ALLOC_MAX];Editor editor = mPreference.edit();// 解析今天的天气int todayIdex = 7;String []icons = new String[2];parseWeatherinfo(detail, todayIdex, weatheBytes, icons);String todayWeather = new String(weatheBytes);log("today:"+todayWeather+ "iconToday:"+icons[0]+" "+icons[1]);//显示天气图片showWeatherIcons(mTodayIV1, mTodayIV2, icons);//text ViewmTodayTV.setText(todayWeather);//save firstdayeditor.putString(LASTSEL_FIRST_DAY_ICONS, new StringBuilder().append(icons[0]).append(",").append(icons[1]).toString());editor.putString(LASTSEL_FIRST_DAY_WEATHER, todayWeather);//解析明天的天气情况int tomorrowIdex = 12;parseWeatherinfo(detail, tomorrowIdex, weatheBytes, icons);String tomorrowWeather = new String(weatheBytes);log("tomorrow:"+tomorrowWeather+ "iconTomorrow:"+icons[0]+" "+icons[1]);//显示天气图片showWeatherIcons(mTomorrowIV1, mTomorrowIV2, icons);//text ViewmTomorrowTV.setText(tomorrowWeather);//save secondeditor.putString(LASTSEL_SECOND_DAY_ICONS, new StringBuilder().append(icons[0]).append(",").append(icons[1]).toString());editor.putString(LASTSEL_SECOND_DAY_WEATHER, tomorrowWeather);//解析后天的天气情况int afterdayIdex = 17;parseWeatherinfo(detail, afterdayIdex, weatheBytes, icons);String afterdayWeather = new String(weatheBytes);log("afterday:"+afterdayWeather+ "iconTomorrow:"+icons[0]+" "+icons[1]);//显示天气图片showWeatherIcons(mAfterdayIV1, mAfterdayIV2, icons);//text ViewmAfterdayTV.setText(afterdayWeather);//save editor.putString(LASTSEL_THIRD_DAY_ICONS, new StringBuilder().append(icons[0]).append(",").append(icons[1]).toString());editor.putString(LASTSEL_THIRD_DAY_WEATHER, afterdayWeather);//the fourth day weatherint fourthIdex = 22;parseWeatherinfo(detail, fourthIdex, weatheBytes, icons);String fourthWeather = new String(weatheBytes);log("afterday:"+fourthIdex+ "iconTomorrow:"+icons[0]+" "+icons[1]);//显示天气图片showWeatherIcons(mFourthIV1, mFourthIV2, icons);//text ViewmFourthTV.setText(fourthWeather);//save editor.putString(LASTSEL_FOURTH_DAY_ICONS, new StringBuilder().append(icons[0]).append(",").append(icons[1]).toString());editor.putString(LASTSEL_FOURTH_DAY_WEATHER, fourthWeather);////the fourth day weatherint fifthIdex = 27;parseWeatherinfo(detail, fifthIdex, weatheBytes, icons);String fifthWeather = new String(weatheBytes);log("afterday:"+fourthIdex+ "iconTomorrow:"+icons[0]+" "+icons[1]);//显示天气图片showWeatherIcons(mFifthIV1, mFifthIV2, icons);//text ViewmFifthTV.setText(fifthWeather);//save editor.putString(LASTSEL_FIFTH_DAY_ICONS, new StringBuilder().append(icons[0]).append(",").append(icons[1]).toString());editor.putString(LASTSEL_FIFTH_DAY_WEATHER, fifthWeather);editor.commit();//}private void showLastWeather() {// TODO Auto-generated method stublog("showLastWeather");//显示天气图片String []icons = new String[2];String weather;String iconStr = mPreference.getString(LASTSEL_FIFTH_DAY_ICONS, "");//image Viewsif(!"".equals(iconStr)){icons = iconStr.split(",");showWeatherIcons(mTodayIV1, mTodayIV2, icons);     }//text ViewmTodayTV.setText(mPreference.getString(LASTSEL_FIRST_DAY_WEATHER, getResources().getString(R.string.weather_def)));///--------------------------///iconStr = mPreference.getString(LASTSEL_SECOND_DAY_ICONS, "");//image Viewsif(!"".equals(iconStr)){icons = iconStr.split(",");showWeatherIcons(mTomorrowIV1, mTomorrowIV2, icons);       }//text ViewmTomorrowTV.setText(mPreference.getString(LASTSEL_SECOND_DAY_WEATHER, getResources().getString(R.string.weather_def)));///--------------------------///iconStr = mPreference.getString(LASTSEL_THIRD_DAY_ICONS, "");if(!"".equals(iconStr)){icons = iconStr.split(",");//image ViewsshowWeatherIcons(mAfterdayIV1, mFifthIV2, icons);       }//text ViewmAfterdayTV.setText(mPreference.getString(LASTSEL_THIRD_DAY_WEATHER, getResources().getString(R.string.weather_def)));///--------------------------///iconStr = mPreference.getString(LASTSEL_FOURTH_DAY_ICONS, "");if(!"".equals(iconStr)){icons = iconStr.split(",");//image ViewsshowWeatherIcons(mFourthIV1, mFourthIV2, icons);        }//text ViewmFourthTV.setText(mPreference.getString(LASTSEL_FOURTH_DAY_WEATHER, getResources().getString(R.string.weather_def)));///--------------------------///iconStr = mPreference.getString(LASTSEL_FIFTH_DAY_ICONS, "");if(!"".equals(iconStr)){icons = iconStr.split(",");//image ViewsshowWeatherIcons(mFifthIV1, mFifthIV2, icons);        }//text ViewmFifthTV.setText(mPreference.getString(LASTSEL_FIFTH_DAY_WEATHER, getResources().getString(R.string.weather_def)));}private void showWeatherIcons(ImageView imageView1, ImageView imageView2, String[] icons) {Resources res = getResources();// image1String resStr = "weather_"+icons[0];int resID = res.getIdentifier(resStr, "drawable", getPackageName());log("showWeatherIcons :  -- image1 to show: "+resStr + " id="+resID);imageView1.setImageResource(resID);//image2resStr = "weather_"+icons[1];resID = res.getIdentifier(resStr, "drawable", getPackageName());log("showWeatherIcons :  -- image2 to show: "+resStr + " id="+resID);imageView2.setImageResource(resID);     }private void parseWeatherinfo(SoapObject detail, int todayIdex, byte[] outWeather, String[] outIcons) {//resourceResources resources = getResources();//解析今天的天气情况StringBuilder weather = new StringBuilder();String date = detail.getProperty(todayIdex).toString();weather.append(resources.getString(R.string.date));weather.append(date.split(" ")[0]);  //得到  4月12日 weather.append("\n");  //换行weather.append(resources.getString(R.string.weathe));  weather.append(date.split(" ")[1]);  //得到 中雨转小雨weather.append("\n");  //换行weather.append(resources.getString(R.string.temperature));  weather.append(detail.getProperty(todayIdex+1));  //得到 13℃/17℃weather.append("\n");  //换行weather.append(resources.getString(R.string.wind));  weather.append(detail.getProperty(todayIdex+2));  //得到 东南风4-5级转北风4-5级log("parseWeatherinfo: "+ weather);String icons[] = new String[2];String imageStr1 = detail.getProperty(todayIdex+3).toString();icons[0] = imageStr1.substring(0, imageStr1.lastIndexOf("."));icons[1] = detail.getProperty(todayIdex+4).toString().substring(0, detail.getProperty(11).toString().lastIndexOf("."));log("parseWeatherinfo: "+icons[0] + "  "+ icons[1]);//returnint length = weather.toString().getBytes().length < WEATHER_ALLOC_MAX ? weather.toString().getBytes().length : WEATHER_ALLOC_MAX;System.arraycopy(weather.toString().getBytes(), 0, outWeather, 0, length);System.arraycopy(icons, 0, outIcons, 0, icons.length);}private static final String TAG = "WeatherForecast";private boolean DEBUG = true;/*** @param string*/private void log(String string) {// TODO Auto-generated method stubif(DEBUG){Log.d(TAG, "--- " + string + " ---");}}/*** */private void initControls() {// TODO Auto-generated method stubmProvinceSpinner = (Spinner) findViewById(R.id.province_spin);mCitySpinner = (Spinner) findViewById(R.id.city_spin);//today controlsmTodayIV1 = (ImageView) findViewById(R.id.today_iv1);mTodayIV2 = (ImageView) findViewById(R.id.today_iv2);mTodayTV = (TextView) findViewById(R.id.today_tv);//tomorrow controlsmTomorrowIV1 = (ImageView) findViewById(R.id.tomorrow_iv1);mTomorrowIV2 = (ImageView) findViewById(R.id.tomorrow_iv2);mTomorrowTV = (TextView) findViewById(R.id.tomorrow_tv);//afterday controlsmAfterdayIV1 = (ImageView) findViewById(R.id.afterday_iv1);mAfterdayIV2 = (ImageView) findViewById(R.id.afterday_iv2);mAfterdayTV = (TextView) findViewById(R.id.afterday_tv);//the fourth controlsmFourthIV1 = (ImageView) findViewById(R.id.fourth_iv1);mFourthIV2 = (ImageView) findViewById(R.id.fourth_iv2);mFourthTV = (TextView) findViewById(R.id.fourth_tv);//the fifth controlsmFifthIV1 = (ImageView) findViewById(R.id.fifth_iv1);mFifthIV2 = (ImageView) findViewById(R.id.fifth_iv2);mFifthTV = (TextView) findViewById(R.id.fifth_tv);//get shemPreference = getSharedPreferences(weather_setting, Context.MODE_PRIVATE);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

附图:(默认界面,没有连接网络时的截图)

Android 使用 ksoap2-android调用Web Service学习相关推荐

  1. android调用web service(cxf)实例

    Google为ndroid平台开发Web Service提供了支持,提供了Ksoap2-android相关架包 1.下载该夹包可以直接登录http://code.google.com/p/ksoap2 ...

  2. 调用Web Service实现天气预报

    随时随地技术实战干货,获取项目源码.学习资料,请关注源代码社区公众号(ydmsq666) 一.概念:Web Service用于消除不同平台.不同语言之间的实现差异,将现有的应用程序发布成开放式服务,从 ...

  3. Web Service学习笔记

    Web Service概述 Web Service的定义 W3C组织对其的定义例如以下,它是一个软件系统,为了支持跨网络的机器间相互操作交互而设计.Web Service服务通常被定义为一组模块化的A ...

  4. 用cxf公布和调用web service

    用cxf发布和调用web service 最近我们的系统需要和一个第三方系统对接,对接的方式是通过web service,所以就学习了一下这方面的东西 用CXF来做web service是比较简单的, ...

  5. C#之VS2010ASP.NET页面调用Web Service和winform程序调用Web Service

    一:用ASP.NET调用Web Service 打开VS2010,打开"文件-新建-网站",选择"ASP.NET网站" 选好存储位置,语言后点击确定,进入默认页 ...

  6. JAVA 调用Web Service

    JAVA 调用Web Service的方法 1.使用HttpClient  用到的jar文件:commons-httpclient-3.1.jar  方法:  预先定义好Soap请求数据,可以借助于X ...

  7. Spring Web Service 学习之Hello World篇

    http://fuxueliang.iteye.com/blog/175184 Spring Web Service是Spring社区基于Spring提供的一个关注于创建"文档驱动" ...

  8. 使用ASP.NET AJAX异步调用Web Service和页面中的类方法(2):处理异步调用中的异常...

    本文来自<ASP.NET AJAX程序设计 第II卷:客户端Microsoft AJAX Library相关>的第三章<异步调用Web Service和页面中的类方法>,请同时 ...

  9. Web Service学习笔记(4)

    代理类文件: 在客户端使用程序中生成的Reference.cs的文件即代理类,Service1.wsdl为相应的XML文件 代理类说明: 1. 代理类开始是引出一系列的命名空间,代码的主题是定义一个跟 ...

最新文章

  1. 在JS中最常看到切最容易迷惑的语法(转)
  2. Source Insight 4怎么取消函数结束提示字符
  3. 一对多关系(one-to-many)
  4. Vue 实现ToDoList
  5. static 与 extern 关键字描述说明
  6. 微信公众平台网站开发JS_SDK遇到的bug——wx.config注册提示成功,但部分接口注册失败问题
  7. 开发指南专题十六:JEECG微云快速开发平台Excel导出
  8. 利用matlab函数创建数组
  9. 在VM环境下安装iKuai(爱快)软路由——适合小白(最新最全教程)
  10. 如何将epub电子书格式转换成txt文本
  11. align latex 使用_LaTeX系列笔记(9)-数学模式下的间距及align等环境的实现
  12. 变额年金(一、 递增年金)
  13. 大数据在金融行业的应用
  14. 服务器(CentOS7)配置R以及R Studio Server
  15. 黑马C++笔记——STL常用算法
  16. webstorm 扩大内存
  17. CreateFileMapping 、MapViewOfFile、UnmapViewOfFile函数用法及示例
  18. 2020年2月12日学习记录
  19. php9宫格抽奖程序_PHP实现抽奖功能实例代码
  20. 配置Anaconda中Jupyter Notebook的默认启动目录

热门文章

  1. TensorFlow深度学习!构建神经网络预测股票!
  2. 杰理之使用 mic_rec_play_start()测试 mic 无声的解决方法【篇】
  3. K8s安全管理:认证、授权、准入控制
  4. 静生定,定生慧,慧至从容
  5. XiaoMi-Ruby-15.6-UMA-only黑苹果efi引导文件
  6. 配置管理和变更管理_想要改善变更管理,消除对它的需要
  7. OnActionExecuting 中设置跳转指定网址或路由
  8. 2.8.1 矩阵的合同
  9. 弱电人要学习的网络安全基础知识
  10. activity启动模式你所不知道的异常情况