I am trying to get my current location and get the driving directions to some destination. I am able to get my location and when I execute the code for the driving directions I get android.os.NetworkOnMainThreadException in the following line
HttpResponse response = httpClient.execute(httpPost, localContext);
Response is NULL. What do i do ?
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode="+mode;
try {
new DownloadWebpageTask().execute(url);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You can't do network operations on the main UI thread. What you will have to do is create a new Thread and do the network stuff there. If you need to, you can then you can post updates back to the main UI thread using a Handler. If you need a code sample, I can post a minimal one that should work.
It's important when you do this NOT to maintain a strong reference back to the Activity or you can leak the whole activity on a device rotate or other onDestroy() event. Because you're passing the Context out to a different thread, you'll want to test this to make sure you're not leaking. I wrote a blog post about this on my Tumblr:
http://tmblr.co/ZSJA4p13azutu
Edit 1
Here's some code that should help:
As
NetworkOnMainThreadException
states , network request should be executed only in background thread. Your cannot execute in main thread.Create an
AsycTask
and execute your code ondoInBackground()
method. Once the background operation is completed, You can update the UI inonPostExecute
This is cause when you are trying to do networking on the main thread.. it should be done on the background thread..
solution: AsyncTask
Click here to learn about AsyncTask