0

i need to send data on url onLocationChanges method,m trying to accomplish the task with following code,but m getting error,can someone help me out? My program crash with following code

    @Override
    public void onLocationChanged(Location location) throws NetworkOnMainThreadException {
    txtLat = (TextView) findViewById(R.id.address_textview);
    txtLat.setText("Latitude:" + location.getLatitude() + ",         Longitude:"         +         location.getLongitude());

String strUrl="http://www.test.com/location.php?location="+location.getLatitude();
try {
    url = new URL(strUrl);
} catch (MalformedURLException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}
try {
    urlConnection = (HttpURLConnection) url.openConnection();
      urlConnection.connect();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
    }
amrit
  • 15
  • 7
  • [`NetworkOnMainThreadException`?](http://stackoverflow.com/search?q=NetworkOnMainThreadException) – MH. Sep 28 '15 at 12:01
  • I would suggest to click on the previous comment. Declaring that your method throws `NetworkOnMainThreadException` is going to help you absolutely zilch. The answers to the plethora of questions on this specific exception should more than suffice. – MH. Sep 28 '15 at 12:09
  • Why throws NetworkOnMainThreadException? you should make sure that cant happen instead of throwing it, make the request on a separate thread. – Nanoc Sep 28 '15 at 12:47
  • Can u guys please explain.. Actually I m a Web developer and new to Android environment.. – amrit Sep 28 '15 at 14:25

2 Answers2

0

You cannot do network I/O in onLocationChanged(). You'll need to start a background Thread in onLocationChanged(). The background Thread can then do the network I/O.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
0

you can write following code on your MainActivity.java class's onCreate()

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Ganpat Kaliya
  • 888
  • 2
  • 9
  • 16
  • This is not a good idea in this case. Network I/O can take a long long time (socket timeouts and DNS timeouts are minutes long). In this case you can block the main (UI) thread for way too long. It is never a good idea to do network I/O on the main thread. OP should be doing network I/O on a background thread. – David Wasser Sep 29 '15 at 10:22