0

I'm trying to get an xml from a url, but I have a bug in HttpResponse.

The URL is for example as follows:

http://maps.googleapis.com/maps/api/directions/xml?origin=43.364876,-5.8654205&destination=43.545686,-5.664482&sensor=true

And my code is:

public String getXML (String url){

            String result = null;
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpPost = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity);
            } catch (Exception ex) {
                Toast errorToast =
                        Toast.makeText(getApplicationContext(),
                                "Error reading xml", Toast.LENGTH_LONG);
                errorToast.show();
            }
            return result;
}

I've already set the internet permission in the manifest. The error is in the line:

HttpResponse httpResponse = httpClient.execute(httpPost);

and shows an error:

android.os.NetworkOnMainThreadException

Thank you

5 Answers5

1

You should create a new thread as fetching the data could take a long time, thus blocking the UI thread. This is reason why you get android.os.NetworkOnMainThreadException.

Try this,

new Thread(new Runnable() {

        @Override
        public void run() {
            // Your code here.

        }
    }).start();

Alternative to this solution is using AsyncTask, which is provided in android. It has doInBackground method which runs on a background thread.

Harshal Kshatriya
  • 5,630
  • 11
  • 44
  • 60
1

Instead of calling getXML(); directly, you write this snippet in your main method:

    {
            ...
            String[] params = new String[]{url}; 
            AsyncPostData apd = new AsyncPostData ();
            apd.execute(params);
            ...        
    }

Define your Async Task like below:

private class AsyncPostData extends AsyncTask<String, Void, Void> {

    @Override
    protected Void doInBackground(String... params) {
        getXML (params[0])
        return null;
    }

}
PrincessLeiha
  • 3,144
  • 4
  • 32
  • 53
0
I think we have a same query here

cant get xml file from an URL in android

Community
  • 1
  • 1
jad
  • 493
  • 3
  • 16
0

I'll just repost this from a different question asked earlier today:

You're trying to run a network request on the main UI thread. Android does not allow you to do that since 3.0 (I believe). Doing so causes your UI to lock up until the request is completed, rendering your app useless during the execution of the request.

You'll either have to run your request in a new Thread or an ASyncTask, to take the load of the UI thread. You can find more info on how to use multiple threads here.

Sander van't Veer
  • 5,930
  • 5
  • 35
  • 50
0

Android Devices with 4+ OS versions not allows to call webservices from main activity. your have HTTP request on activity, so you have got "android.os.NetworkOnMainThreadException"

I recommend you go for the AsyncTask solution. It is an easy and straightforward way of running requests or any other background tasks and calling web services using devices having latest OS virsion you must need to use AsyncTask.

It's also easy to implement e.g. onProgressUpdate if you need to show a progress bar of some sort while running your requests.

private class YourTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
    //call your methods from here
         //publish yor progress here..
        publishProgress((int) ((i / (float) count) * 100));
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
    //action after execution success or not
 }
}
Swapnil Kotwal
  • 5,418
  • 6
  • 48
  • 92