Ari*_*MAZ 0 java android web-services android-asynctask
我正在调用soap webservice并需要显示返回的内容.但我不能这样做,因为AsyncTask很复杂,我不知道如何正确使用它.你能告诉我如何通过asynctask从被调用函数返回数据吗?
这是我的代码
public class WebserviceTool {
private final String NAMESPACE = "http://tempuri.org/";
private final String URL = "http://192.168.0.11:9289/Service1.asmx";
private final String SOAP_ACTION = "http://tempuri.org/get_currency";
private final String METHOD_NAME = "get_currency";
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public String execute_barcode_webservice(String s1, String s2) {
//Create request
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("date",s1);
request.addProperty("cur_code",s2);
//Create envelope
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.encodingStyle = SoapEnvelope.ENC;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Object response;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
response = (Object) envelope.getResponse();
Log.i("my_error", response.toString());
} catch (Exception e) {
Log.i("my_error", e.getMessage().toString());
}
return "testarif";
}
public class AsyncCallWS extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
try {
execute_barcode_webservice(params[0], params[1]);
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
@Override
protected void onPostExecute(Void result) {
}
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Void... values) {
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是执行所有作业并返回数据的函数execute_barcode_webservice().但是因为我调用execute_barcode_webservice()查看AsyncTask,我不知道如何返回它.我该怎么做?
异步任务执行的结果是由response生成的对象execute_barcode_webservice().但是,不要将异步任务视为将执行并向您返回值的事物.相反,在方法内部,onPostExecute()您必须获取response对象并对其进行处理(提取其值并将其显示在列表中,或者您要对其执行的任何操作).异步任务只是一种在单独的线程中执行某些代码然后返回主线程(UI线程)并处理结果的方法,这是完成的onPostExecute().
我的建议:重写execute_barcode_webservice()以返回一个response对象而不是一个String(null如果操作失败可以是一个对象)并将该对象传递给该onPostExecute()方法.您必须将异步任务更改为:
public class AsyncCallWS extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... params) {
Object response = null;
try {
response = execute_barcode_webservice(params[0], params[1]);
} catch (Exception e) {
// TODO: handle exception
}
return response;
}
@Override
protected void onPostExecute(Object response) {
if (response != null) {
// display results in a list or something else
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
677 次 |
| 最近记录: |