01
2014
07

Android开发学习:WebService实例:天气情况查询

Android开发学习

Android开发中,经常见到通过WebService接口进行数据访问查询,介绍一下网上找到的天气情况查询实例

实例:天气情况查询

新建布局文件:activity_main.xml,使用ListView显示地区列表,代码内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/province_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="@android:color/transparent"
        android:fadingEdge="none" >
    </ListView>

</RelativeLayout>

新建weather_layout.xml来显示具体查询出来的天气详细信息,代码内容:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/weather"
                android:textColor="#336598"
                android:textSize="16sp"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

实现的MainActivity.java代码如下:

package com.zhengdecai.webserviceinfo;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.zhengdecai.utils.ProgressDialogUtils;
import com.zhengdecai.utils.WebServiceUtils;
import com.zhengdecai.utils.WebServiceUtils.WebServiceCallBack;

/**
 * WebService实例:天气情况查询-显示天气省份的Activity、MainActivity显示地区列表、CityActivity二级城市列表、WeatherActivity天气详细、WebServiceUtils操作
 *
 * @author 郑德才
 *
 */
public class MainActivity extends Activity {
 private List<String> provinceList = new ArrayList<String>();

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  init();
 }

 private void init() {
  final ListView mProvinceList = (ListView) findViewById(R.id.province_list);
  
  //显示进度条
  ProgressDialogUtils.showProgressDialog(this, "数据加载中...");
  
  //通过工具类调用WebService接口
  WebServiceUtils.callWebService(WebServiceUtils.WEB_SERVER_URL, "getSupportProvince", null, new WebServiceCallBack() {
   //WebService接口返回的数据回调到这个方法中
   @Override
   public void callBack(SoapObject result) {
    //关闭进度条
    ProgressDialogUtils.dismissProgressDialog();
    if(result != null){
     provinceList = parseSoapObject(result);
     mProvinceList.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, provinceList));
    }else{
     Toast.makeText(MainActivity.this, "获取WebService数据错误", Toast.LENGTH_SHORT).show();
    }
   }
  });
  
  mProvinceList.setOnItemClickListener(new OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
    Intent intent = new Intent(MainActivity.this, CityActivity.class);
    intent.putExtra("province", provinceList.get(position));
    startActivity(intent);
   }
  });
  
  
 }
 
 /**
  * 解析SoapObject对象
  * @param result
  * @return
  */
 private List<String> parseSoapObject(SoapObject result){
  List<String> list = new ArrayList<String>();
  SoapObject provinceSoapObject = (SoapObject) result.getProperty("getSupportProvinceResult");
  if(provinceSoapObject == null) {
   return null;
  }
  for(int i=0; i<provinceSoapObject.getPropertyCount(); i++){
   list.add(provinceSoapObject.getProperty(i).toString());
  }
  return list;
 }
}

主要通过操作类来实现对WebService数据的读取WebServiceUtils.java,代码内容:

package com.zhengdecai.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.os.Handler;
import android.os.Message;

/**
 * WebService实例:访问WebService的工具类,
 *
 * @author 郑德才
 *
 */
public class WebServiceUtils {
 public static final String WEB_SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";
 // 含有3个线程的线程池
 private static final ExecutorService executorService = Executors
   .newFixedThreadPool(3);
 // 命名空间
 private static final String NAMESPACE = "http://WebXml.com.cn/";

 /**
  *
  * @param url
  *            WebService服务器地址
  * @param methodName
  *            WebService的调用方法名
  * @param properties
  *            WebService的参数
  * @param webServiceCallBack
  *            回调接口
  */
 public static void callWebService(String url, final String methodName,
   HashMap<String, String> properties,
   final WebServiceCallBack webServiceCallBack) {
  // 创建HttpTransportSE对象,传递WebService服务器地址
  final HttpTransportSE httpTransportSE = new HttpTransportSE(url);
  // 创建SoapObject对象
  SoapObject soapObject = new SoapObject(NAMESPACE, methodName);

  // SoapObject添加参数
  if (properties != null) {
   for (Iterator<Map.Entry<String, String>> it = properties.entrySet()
     .iterator(); it.hasNext();) {
    Map.Entry<String, String> entry = it.next();
    soapObject.addProperty(entry.getKey(), entry.getValue());
   }
  }

  // 实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号
  final SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
    SoapEnvelope.VER11);
  // 设置是否调用的是.Net开发的WebService
  soapEnvelope.setOutputSoapObject(soapObject);
  soapEnvelope.dotNet = true;
  httpTransportSE.debug = true;

  // 用于子线程与主线程通信的Handler
  final Handler mHandler = new Handler() {

   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    // 将返回值回调到callBack的参数中
    webServiceCallBack.callBack((SoapObject) msg.obj);
   }

  };

  // 开启线程去访问WebService
  executorService.submit(new Runnable() {

   @Override
   public void run() {
    SoapObject resultSoapObject = null;
    try {
     httpTransportSE.call(NAMESPACE + methodName, soapEnvelope);
     if (soapEnvelope.getResponse() != null) {
      // 获取服务器响应返回的SoapObject
      resultSoapObject = (SoapObject) soapEnvelope.bodyIn;
     }
    } catch (HttpResponseException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    } catch (XmlPullParserException e) {
     e.printStackTrace();
    } finally {
     // 将获取的消息利用Handler发送到主线程
     mHandler.sendMessage(mHandler.obtainMessage(0,
       resultSoapObject));
    }
   }
  });
 }

 /**
  *
  *
  * @author 郑德才
  *
  */
 public interface WebServiceCallBack {
  public void callBack(SoapObject result);
 }
}

模拟器上的效果:

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。