繁体   English   中英

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

[英]How to call Web Service in OnCreate() android

我想打电话给Web服务获取一些必须在“我的第一屏幕”中显示的数据。 我在OnCreate()使用过,它引发了一些异常。 如何在OnCreate()方法中调用Web服务?

因此,您想从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服务,而不会出现错误。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM