我正在开发Android应用并遇到问题。问题是onPostExecute不会在每次事件doInBackground成功执行并且返回true时执行。我的代码如下。请帮助我,我遇到了大麻烦。
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
msgtouser.setText("Wait we are fetching HOT DEALS...");
}
@Override
protected Boolean doInBackground(String... urls) {
Boolean retValue = false;
try {
HttpResponse response = null;
String CSRFTOKEN = "";
// Create a new HttpClient and Post Header
DefaultHttpClient httpClient = new DefaultHttpClient();
// Access POST route using CSRFTOKEN
HttpPost httppost = new HttpPost(urls[0]);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("_token", CSRFTOKEN));
nameValuePairs.add(new BasicNameValuePair("uid", urls[1]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpClient.execute(httppost);
} catch (Exception e) {
ccode.ErrorReporting(e);
}
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("hotdeal");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
HotDeals objHD = new HotDeals();
objHD.setId(object.getInt("offid"));
objHD.setName(object.getString("line1"));
objHD.setLocation(object.getString("line3"));
objHD.setDistance(object.getString("dist"));
objHD.setOffer(object.getString("line2"));
objHD.setImage(object.getString("ban"));
dealsList.add(objHD);
}
retValue = true;
}
} catch (Exception e) {
ccode.ErrorReporting(e);
}
return retValue;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
dialog.cancel();
// adapter.notifyDataSetChanged();
if (result == false && AppConstants.ISDEBUG) {
Toast.makeText(getActivity().getApplicationContext(), "Hot Deals : Network Error", Toast.LENGTH_LONG)
.show();
} else {
if (dealsList.isEmpty()) {
msgtouser.setText("Sorry, there are no HOT DEALS for the location selected by you");
} else {
msgtouser.setVisibility(View.GONE);
ListView listview = (ListView) rootView.findViewById(R.id.listhd);
adapter = new HotDealsAdapter(HotDealsFragment.this.getActivity(), R.layout.hotdeals_row,
dealsList);
listview.setAdapter(adapter);
}
}
}
}
答案 0 :(得分:0)
你不需要调用super.onPostExecute()(不确定它是否可能导致问题,但不需要)如果这不是问题,那么下面......
我“想”我知道问题是什么......我们之前遇到过......如果您在旋转手机(或任何其他硬件更改)时发生这种情况......
然后问题是doInBackground()
的返回值实际上没有传递给onPostExecute()
并且你将传入一个null。(如果硬件更改发生在{{ 1}})
然而,这似乎与您的描述中的“完全”不同。 'onPostExecute()'根本不运行是奇怪的。你应该把一个logcat语句作为方法中的第一件事,看看是否记录了。
因为'false'是doInBackground()
的默认值所以它可能就是你所描述的那个你没有'else'部分的地方,但你应该得到吐司呢...
因此,在doInBackground返回之前登录两个位置(1),在onPostExecute()的最开始登录(2)并查看值是否“同意”