當按鈕被點擊doInbackground不叫
new HttpAsyncTasks().execute("http://www.demo.com/xyz");
這是上面的執行
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永遠不會被執行,但中的AsyncTask執行此網址onPostExecute方法。
這就是所謂的doInbackground
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;
}
的帖子方法請什麼地方出錯了?
只是檢查。你確定POST()方法ID沒有被調用,並且情況不是所說的函數返回null嗎? –
這不是因爲我在該方法中添加了Toast。永遠不會執行 – Blaze
嘗試記錄或調試,我很確定它正在執行 –