-2

In my app I want to parse a weather xml api but exception arises while parsing the URL of the api. Here is screen shot of logcat.

enter image description here

From the logcat observation the exception arises at line 654 and I have xr.parse(new InputSource(url.openStream())); statement at line 654 but, I dont know how solve the issue.You can check the statement in below code. Please help me in this respect. Your response would be highly appreciated. Thanks in advance.

Here is my code.

private void parseWeatherURL(String strURL)
 {
     try
     {
         String weatherURL="http://api.worldweatheronline.com/free/v1/weather.ashx?key=476yv2t87x67j5pzb7hbazn6&q=34.25,71.014&cc=yes&num_of_days=5&format=xml";
         /* Replace blanks with HTML-Equivalent. */ 
         URL url = new URL(weatherURL.replace(" ", "%20"));
         Log.e("Weather", "URL");   

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        Log.e("Weather", "SAX");

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        com.ifahja.weather.WeatherHandler myWeatherHandler = new com.ifahja.weather.WeatherHandler();
        xr.setContentHandler(myWeatherHandler);
        Log.e("Weather", "Handler");
        /* Parse the xml-data our URL-call returned. */
        xr.parse(new InputSource(url.openStream()));

        //Log.d(TAG, "it's all right");

        Log.e("Weather URL", "it's all right");

     }
     catch(Exception e)
     {
         Log.e("Problem", "parseWeatherURL()");
         e.printStackTrace();
     }
 }
user2391890
  • 639
  • 1
  • 8
  • 15

2 Answers2

1

Are you making a network call outside the UI thread? Because you have NetworkOnMainThreadException...

If not, use an AsyncTask. For example:

Or

You can use Android Asynchronous Http Client library. Very simple library, tiny size (25kb), easy to use, and asynchronous. The code will be something like :

AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.dfsdfsdfsdfsd.com", new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
      // Here is your content !
    }
});

Available here.


Otherwise, you may want to cut your call into separate call and check for null value

URLConnection urlcon = url.openConnection();
urlcon.setReadTimeout(10000);
InputStream is = urlcon.getInputStream();
Jason L
  • 1,812
  • 2
  • 22
  • 43
azerto00
  • 1,001
  • 6
  • 18
0

You can't make this call on the main UI thread. Try creating an AsyncTask and then call the method in it. http://developer.android.com/reference/android/os/AsyncTask.html

Embattled Swag
  • 1,479
  • 12
  • 23