我有一个像这样的标准 AsyncTask:
// starting AsyncTask in onCreate
new TaskName().execute();
class TaskName extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(Items.this);
private InputStream is = null;
private String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Loading...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
TaskName.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = "my_link.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("Category", Category));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No items!",
Toast.LENGTH_SHORT).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
progressDialog.dismiss();
}
}
但是,我发现自己有三个几乎相同的 AsyncTasks 在做同样的事情。访问 PHP 文件,解析 JSON 并打印 JSON。
我搜索了一段时间,看看是否有可以使用的标准类,但我找不到。有没有办法让这更有效,所以我不会重复这么多次?