Jos*_*ley 5 android http-post android-asynctask networkonmainthread
我建立一个应用程序,我得到一个NetworkOnMainThreadException INSIDE的的AsyncTask
呼叫:
new POST(this).execute("");
Run Code Online (Sandbox Code Playgroud)
的AsyncTask:
public class POST extends AsyncTask<String, Integer, HttpResponse>{
private MainActivity form;
public POST(MainActivity form){
this.form = form;
}
@Override
protected HttpResponse doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost("http://diarwe.com:8080/account/login");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",((EditText)form.findViewById(R.id.in_email)).getText().toString()));
//add more...
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
return new DefaultHttpClient().execute(httppost);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
return null;
}
@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
try {
Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
}
}
Run Code Online (Sandbox Code Playgroud)
logcat的:
BackgroundError | android.os.NetworkOnMainThreadException
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么在异步任务的doInBackground中的do中抛出这个异常,任何想法?
将JSON
代码移动到doInBackground()
:
@Override
protected HttpResponse doInBackground(String... params) {
...
Your current HttpPost code...
...
Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6031 次 |
最近记录: |