[英]doInbackground of asyncktask is not called
單擊按鈕時執行該URL
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
這是上面執行的asynctask
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return POSTS(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "successfull!", Toast.LENGTH_LONG).show();
//call main activity activity upon successful registration
Intent callMain = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(callMain);
}
}
上面的doInbackground永遠不會執行,但是onPostExecute方法會執行。
這是在doInbackground中調用的POSTS方法
public String POSTS(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("xyz", "xyz");
jsonObject.accumulate("amount", "800");
jsonObject.accumulate("demo", "demo");
jsonObject.accumulate("demo2", demo2);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
請問可能有什么問題嗎?
你能嘗試一下嗎? 它正在檢查您的POSTS方法。 如果Toast顯示空行,則說明您在WebProcess上的POSTS方法中出錯。
private class HttpAsyncTasks extends AsyncTask<String, Void, String> {
private String myResult="check";
@Override
protected String doInBackground(String... urls) {
try
{
myResult = POSTS(urls[0]);
}
catch(Exception e)
{
return e;
}
return myResult;
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
/* other codes */
}
}
您的POSTS(urls [0])調用必須給出一個異常,並且當它執行此操作時,其余的代碼將被跳過,並繞過您的敬酒。 嘗試刪除異常,您可以在logcat中找到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.