所以我有这个扩展 AsyncTask 的加载器类。那我就做new loader().execute();
但我想用JSONArray 响应我的加载器类returns我怎么做?因为我在几个不同的地方都需要它?或者我应该将代码移至 onPostExecute 并从那里执行所有操作?
public class loader extends AsyncTask<String, Integer, JSONArray> {
ProgressDialog dialog;
protected void onPreExecute() {
dialog = ProgressDialog.show(ChallengeList.this, "", "Laddar...");
dialog.setCancelable(true);
}
@Override
protected JSONArray doInBackground(String... params) {
JSONArray response = null;
HttpClient client = new DefaultHttpClient();
HttpPost httppost = new HttpPost(listURL);
try {
HttpResponse resp = client.execute(httppost);
StatusLine statusLine = resp.getStatusLine();
int statusCode = statusLine.getStatusCode();
Log.i("Statuscode", "statusCode"+statusCode);
if (statusCode == 200) {
final JSONObject json = new JSONObject();
json.put("userID", prefs.id());
response = SendHttp.parseHttp(listURL, json);
}
} catch (JSONException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return response;
}
protected void onPostExecute(JSONArray result) {
dialog.dismiss();
}
}
方法onPostExecute
作为参数JSONArray
你从doInBackground
方法。
onPostExecute
在主(调用者)活动的线程上运行,因此除了在该方法中关闭对话框之外,您还可以处理result
进一步数组,将其安全地传递给其他方法等:
@Override
protected void onPostExecute(JSONArray result)
{
super.onPostExecute(result);
final Message msg = new Message();
msg.obj = result;
if (youWantToUseHandler)
handler.dispatchMessage(msg);
else
writeJSONArray(result);
}
the handler
:
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
final JSONArray result = (JSONArray)msg.obj;
writeJSONArray(result);
};
};
其他一些方法:
private void writeJSONArray(final JSONArray result)
{
for (int i = 0; i < result.length(); i++)
{
try
{
Log.d("SAMPLE", result.get(i).toString());
}
catch (JSONException e)
{
Log.e("SAMPLE", "error getting result " + i, e);
}
}
}
Since onPostExecute
“在 doInBackground 之后在 UI 线程上运行。指定的结果是 doInBackground 返回的值,如果任务被取消或发生异常,则返回 null。” ~API 文档
您可以调用在类中声明的任何方法,并将该数组作为参数传递给它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)