我已经使用 AsyncTask 几天了。我的旧代码可以在 API 8 上使用 runOnUIThred 运行,但不能在 >API 18 上运行。我想在 doInBackground() 中使用 JSON 将数据发送到数据库,并在 onPostExecute() 中获取数据。如何将我的代码分成两部分?
class GetProductDetails extends AsyncTask<String, String, Integer> {
@Override
protected void onPreExecute() {
//bla-bla-bla
}
protected Integer doInBackground(String... args) {
int success = 0;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
JSONObject json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
success = json.getInt(TAG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
protected void onPostExecute(Integer success) {
pDialog.dismiss();
JSONArray productObj = json.getJSONArray(TAG_PRODUCT);
JSONObject product = productObj.getJSONObject(0);
if (success == 1) {
txtName = (TextView) findViewById(R.id.tvName);
txtPrice = (TextView) findViewById(R.id.tvPrice);
txtDesc = (TextView) findViewById(R.id.tvDescription);
txtCurrent = (TextView) findViewById(R.id.tvCurrent);
txtTurn = (TextView) findViewById(R.id.tvTurn);
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
txtCurrent.setText(product.getString("current"));
txtTurn.setText(product.getString("turn"));
}else{ }
}
}
最佳答案
您可以让 doInBackground
返回 JSONObject json
并在 onPostExecute
中使用它。
然后要检查是否一切正常,请在 onPostExecute
中进行检查。
类似于:
class GetProductDetails extends AsyncTask<String, String, JSONObject>
{
@Override
protected void onPreExecute() {
//bla-bla-bla
}
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("pid", pid));
json = jsonParser.makeHttpRequest(
url_product_detials, "GET", params);
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
if (json == null) return; // check if json is null too! if null something went wrong (handle it, i used return as example)
int success = json.getInt(TAG_SUCCESS);;
if (success == 1) {
JSONArray productObj = json.getJSONArray(TAG_PRODUCT);
JSONObject product = productObj.getJSONObject(0);
txtName = (TextView) findViewById(R.id.tvName);
txtPrice = (TextView) findViewById(R.id.tvPrice);
txtDesc = (TextView) findViewById(R.id.tvDescription);
txtCurrent = (TextView) findViewById(R.id.tvCurrent);
txtTurn = (TextView) findViewById(R.id.tvTurn);
txtName.setText(product.getString(TAG_NAME));
txtPrice.setText(product.getString(TAG_PRICE));
txtDesc.setText(product.getString(TAG_DESCRIPTION));
txtCurrent.setText(product.getString("current"));
txtTurn.setText(product.getString("turn"));
}else{
}
}
关于java - 如何在AsyncTask中获取onPostExecute结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22893625/