-2

I using the below code to retrieve the data from the database. I am getting the error "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();
}     }

I have provided permission code to access internet in Manifest file. Could someone please help me with this error. Thanks in advance.

  • You can't do networking on the main thread, it would freeze the UI. You must do it on another thread or AsyncTask. Next time use google, this is answered a dozen times a day. – Gabe Sechan Jun 22 '14 at 00:49

1 Answers1

0

Exactly as the exception states - you cannot perform network operations on the main (UI) thread. The code you posted performs an HttpPost. Look into AsyncTask. See references here: http://developer.android.com/guide/components/processes-and-threads.html and here: http://developer.android.com/reference/android/os/AsyncTask.html

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
KMLong
  • 8,345
  • 2
  • 16
  • 19