Android 使用 ksoap2-android调用Web Service学习
2014-04-13 19:04
441 查看
今天学习《疯狂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
MainActivity.java
附图:(默认界面,没有连接网络时的截图)
该文章中使用到 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 namespace public static final String SERVICE_NS = "http://WebXml.com.cn/"; //web services 提供服务的url public 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 method final String methodName = "getRegionProvince"; //httptra final 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>>() { @Override public List<String> call() throws Exception { //call web services ht.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 stub return null; } }); new Thread(task).start(); try { return task.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.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>>() { @Override public List<String> call() throws Exception { //call web services ht.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 stub return null; } }); new Thread(task).start(); try { return task.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.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>() { @Override public 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 stub return detail; } return null; } }); new Thread(task).start(); try { return task.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.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 data result.add(detail.getProperty(i).toString().split(",")[0]); } // TODO Auto-generated method stub return 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 controls private ImageView mTodayIV1 = null; private ImageView mTodayIV2 = null; private TextView mTodayTV = null; // tomorrow controls private ImageView mTomorrowIV1 = null; private ImageView mTomorrowIV2 = null; private TextView mTomorrowTV = null; // afterday controls private ImageView mAfterdayIV1 = null; private ImageView mAfterdayIV2 = null; private TextView mAfterdayTV = null; // the fourth day controls private ImageView mFourthIV1 = null; private ImageView mFourthIV2 = null; private TextView mFourthTV = null; // the fifth day controls private 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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // int controls initControls(); // 判断是否能连上网络 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 spinner mProvinceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> source, View parent, int position, long id) { // TODO Auto-generated method stub mSelProvince = 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_PROVINCE Editor editor = mPreference.edit(); editor.putString(LASTSEL_PROVINCE, mSelProvince); //吧奥村城市列表 editor.putString(mSelProvince, citiesSB.toString()); editor.commit(); // 显示 城市 spinner if(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); } } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); //city spinner mCitySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub String selCity = mCitySpinner.getSelectedItem().toString(); log("selected city :"+selCity); //get city wather showWeather(selCity); //!!!!!!!!!!!! main fun //保存最后选择的城市 Editor editor = mPreference.edit(); editor.putString(LASTSEL_CITY + mSelProvince, selCity); editor.commit(); } @Override public 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 stub return 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 memory byte[] 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 View mTodayTV.setText(todayWeather); //save firstday editor.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 View mTomorrowTV.setText(tomorrowWeather); //save second editor.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 View mAfterdayTV.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 weather int 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 View mFourthTV.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 weather int 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 View mFifthTV.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 stub log("showLastWeather"); //显示天气图片 String []icons = new String[2]; String weather; String iconStr = mPreference.getString(LASTSEL_FIFTH_DAY_ICONS, ""); //image Views if(!"".equals(iconStr)){ icons = iconStr.split(","); showWeatherIcons(mTodayIV1, mTodayIV2, icons); } //text View mTodayTV.setText(mPreference.getString(LASTSEL_FIRST_DAY_WEATHER, getResources().getString(R.string.weather_def))); ///--------------------------/// iconStr = mPreference.getString(LASTSEL_SECOND_DAY_ICONS, ""); //image Views if(!"".equals(iconStr)){ icons = iconStr.split(","); showWeatherIcons(mTomorrowIV1, mTomorrowIV2, icons); } //text View mTomorrowTV.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 Views showWeatherIcons(mAfterdayIV1, mFifthIV2, icons); } //text View mAfterdayTV.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 Views showWeatherIcons(mFourthIV1, mFourthIV2, icons); } //text View mFourthTV.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 Views showWeatherIcons(mFifthIV1, mFifthIV2, icons); } //text View mFifthTV.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(); // image1 String resStr = "weather_"+icons[0]; int resID = res.getIdentifier(resStr, "drawable", getPackageName()); log("showWeatherIcons : -- image1 to show: "+resStr + " id="+resID); imageView1.setImageResource(resID); //image2 resStr = "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) { //resource Resources 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]); //return int 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 stub if(DEBUG){ Log.d(TAG, "--- " + string + " ---"); } } /** * */ private void initControls() { // TODO Auto-generated method stub mProvinceSpinner = (Spinner) findViewById(R.id.province_spin); mCitySpinner = (Spinner) findViewById(R.id.city_spin); //today controls mTodayIV1 = (ImageView) findViewById(R.id.today_iv1); mTodayIV2 = (ImageView) findViewById(R.id.today_iv2); mTodayTV = (TextView) findViewById(R.id.today_tv); //tomorrow controls mTomorrowIV1 = (ImageView) findViewById(R.id.tomorrow_iv1); mTomorrowIV2 = (ImageView) findViewById(R.id.tomorrow_iv2); mTomorrowTV = (TextView) findViewById(R.id.tomorrow_tv); //afterday controls mAfterdayIV1 = (ImageView) findViewById(R.id.afterday_iv1); mAfterdayIV2 = (ImageView) findViewById(R.id.afterday_iv2); mAfterdayTV = (TextView) findViewById(R.id.afterday_tv); //the fourth controls mFourthIV1 = (ImageView) findViewById(R.id.fourth_iv1); mFourthIV2 = (ImageView) findViewById(R.id.fourth_iv2); mFourthTV = (TextView) findViewById(R.id.fourth_tv); //the fifth controls mFifthIV1 = (ImageView) findViewById(R.id.fifth_iv1); mFifthIV2 = (ImageView) findViewById(R.id.fifth_iv2); mFifthTV = (TextView) findViewById(R.id.fifth_tv); //get she mPreference = getSharedPreferences(weather_setting, Context.MODE_PRIVATE); } @Override public 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调用WebService学习
- Android使用Ksoap2调用Web service传递自定义对象,List,大文件
- Android使用ksoap2-android调用WebService学习
- Android上使用ksoap2支持Web Service服务调用实例
- Android使用ksoap2-android调用WebService学习
- Android使用ksoap2-android调用WebService学习
- Android使用ksoap2-android调用WebService学习
- Android使用ksoap2-android调用WebService学习
- Android使用ksoap2-android调用WebService学习
- 在Android 中使用KSOAP2调用WebService
- 在Android 中使用KSOAP2调用WebService(一)
- 在Android 中使用KSOAP2调用WebService
- 在Android 中使用KSOAP2调用WebService(二)
- android使用ksoap2调用webservice接口返回错误HTTP status: 500
- 使用Ksoap2调用Web Service加入SoapHeader
- android-------使用Android应用调用Web Service
- Android使用KSOAP2等第三方jar包调用WebService出现java.lang.NoClassDefFoundError.的解决办法
- Android使用KSOAP2调用WebService及正确导入jar包的问题
- 学习JNI--Android下使用JNI调用C
- Android使用Json和ksoap2调用WebService(WCF)