-2

我使用下面的代码从数据库中检索数据。我收到错误“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();
}     }

我在 Manifest 文件中提供了访问 Internet 的权限代码。有人可以帮我解决这个错误。提前致谢。

4

1 回答 1

0

正如异常状态 - 您不能在主(UI)线程上执行网络操作。您发布的代码执行 HttpPost。查看 AsyncTask。请参阅此处的参考资料:http: //developer.android.com/guide/components/processes-and-threads.html和此处:http: //developer.android.com/reference/android/os/AsyncTask.html

于 2014-06-22T00:52:54.110 回答