Networking operation on UI Main thread are not allowed.
Try following code.
public class NetRequestAsync extends AsyncTask {
String id, msg;
public NetRequestAsync(String id, String message) {
this.id = id;
this.msg = message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.eeecoderpages.orgfree.com/post.php");
try {
List nameValuePairs = new ArrayList(
2);
nameValuePairs.add(new BasicNameValuePair("id", id));
nameValuePairs.add(new BasicNameValuePair("message", msg));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return true;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if(result){
//successful request
}else{
//error in request response
}
msgTextField.setText(""); // clear text box
}
}
To use this code,
NetRequestAsync request = new NetRequestAsync("12345","Hi");
request.execute();
Note
UI operation like updating TextView, EditText or setting image to ImageView are not allowed in doInBackground()
method. You can do that in onPostExecute()
or onPreExecute()
.