我正在使用asynctask使用Soap请求和响应。我发送json请求并获取响应。但是如何使用此asynctask在公共类中执行请求和响应。这样我就可以通过传递请求和获取响应来使用多个活动。请给我解决方案。怎么解决这个? 到目前为止,我这样做。我为单个asynctask写了。但是对于另一个服务调用,我需要执行另一个asynctask。如何共同使用它并执行。 我已经在代码中发表了评论以便更好地理解。这是我的代码。
class A extend Activity{
private String sessionId;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
new CommonElement().execute();
}
class CommonElement extends AsyncTask<String, String, String> {
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CommonElement.this);
dialog.show();
dialog.setCancelable(false);
}
@Override
protected String doInBackground(String... args) {
try {
// these are all common
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.API_URL);
sessionId = Utils.readPreferences(CommonElement.this,Constants.SESSION_ID, null);
if (sessionId == null) {
SoapObject request = new SoapObject(Constants.NAMESPACE, "login");
request.addProperty("username", "Clothing");
request.addProperty("apiKey", "Clothing");
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
Utils.savePreferences(SortFilterPopupActivity.this,
Constants.SESSION_ID, sessionId);
}// till this it's common
//here json reuest datas varies in json.put()...
SoapObject requests = new SoapObject(Constants.NAMESPACE, "call");//these are common
requests.addProperty("sessionId", sessionId);//these are common
requests.addProperty("resourcePath","sortap.Action"); //this will change for every property
JSONObject json = new JSONObject();// these will change
json.put("page", "1");
json.put("limit", "10");
json.put("name", sortName);
json.put("order", sortOrder);
json.put("id", "3");
json.put("cate_id", "4");
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
//based on various request and response this varies.
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results.toString());
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String id = object.getString("id");
String productName = object.getString("product_name");
String imageUrl = object.getString("image_url");
int productPrice = object.getInt("price");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
}