我使用以下代码从数据库中检索数据。我收到错误" android.os.NetworkOnMainThreadException"。
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
Toast.makeText(getApplicationContext(), "inside try block",Toast.LENGTH_LONG).show();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://129.107.239.106/select.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
Toast.makeText(getApplicationContext(), "entity ",Toast.LENGTH_LONG).show();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
} }
我提供了在清单文件中访问互联网的权限代码。有人可以帮我解决这个错误。提前谢谢。
答案 0 :(得分:0)
正如异常所述 - 您无法在主(UI)线程上执行网络操作。您发布的代码执行HttpPost。查看AsyncTask。请参阅此处的参考资料:http://developer.android.com/guide/components/processes-and-threads.html和此处:http://developer.android.com/reference/android/os/AsyncTask.html