Search code examples
javaandroidandroid-layoutmobilenetworkonmainthread

connecting android app with web server


my connection code is this to get string from website....

url value is http://sagindia.netne.net/sendmail.php

public String makeServiceCall(String url) {
    try {
      // http client
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpEntity httpEntity = null;
      HttpResponse httpResponse = null;

      HttpGet httpGet = new HttpGet(url);
      httpResponse = httpClient.execute(httpGet);
      httpEntity = httpResponse.getEntity();
      response = EntityUtils.toString(httpEntity);
   } catch (Exception e) {

   }
   return response;
}

showing error in line

httpResponse = httpClient.execute(httpGet);

log cat error part..

03-08 15:46:06.951: E/AndroidRuntime(1004): Caused by: anroid.os.NetworkOnMainThreadException

i have rtied to solve this problem , but couldn't solve this...i am first time trying to get response from server....if anybody have solution plz help me..


Solution

  • I have got my answer from provided link by @blackTigher ...

    problem was because of network on main thread...

    so added this code before the connecting to httpclient

     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
     StrictMode.setThreadPolicy(policy);
    

    It worked for me...

    for more detail can visit at NetworkOnMainThreadException