如何在OnCreate()android中调用Web服务

时间:2013-01-03 08:03:32

标签: android

我想调用Web Service来获取必须在我的First屏幕中显示的一些数据。我在OnCreate()中使用过,它会抛出一些异常。如何在OnCreate()方法中调用Web服务?

2 个答案:

答案 0 :(得分:1)

所以你想从OnCreate()调用一个Web服务,而不是使用:

String NAMESPACE = "Target Name Sapce/";
String URL = "URL generated in WSDL";
String SOAP_ACTION = "Name Sapce/Method name";
String METHOD_NAME = "Method Name";

//Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);       

//Use this to add parameters
request.addProperty("Parameter1",Parameter1);
request.addProperty("Parameter2",Parameter2);

//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {              
    androidHttpTransport.debug = true;
    //this is the actual part that will call the  
    androidHttpTransport.call(SOAP_ACTION, envelope);
    // Get the SoapResult from the envelope body.
    SoapObject result = (SoapObject)envelope.bodyIn;
    String validate = result.getProperty(0).toString();

    //Get the first property and change the label text
    Toast.makeText(getApplicationContext(), "Connected "+result.getProperty(0).toString(),Toast.LENGTH_LONG).show();

} catch (Exception e) {
      e.printStackTrace();
}

这将帮助您从OnCreate()调用Web服务而不会出错。

答案 1 :(得分:0)

无论是否在onCreate(),您都不应在 ui线程中进行联网。如果您希望从Web获取数据,可以使用基于this回调的库。覆盖其onStart()以显示某些“请稍候...”内容,并覆盖其onSuccess()onFailure()onFinish()(如果需要)以继续执行。