2013-11-20 47 views
-2

在我的應用程序中,我想解析天氣xml api,但解析api的URL時出現異常。這裏是logcat的屏幕截圖。在Android中的URL解析中出現異常Java

enter image description here

從logcat的觀測異常出現在線路654和我在線路654 xr.parse(new InputSource(url.openStream()));說法,但我不知道如何解決issue.You可以檢查語句下面的代碼。請在這方面幫助我。您的迴應將不勝感激。提前致謝。

這是我的代碼。

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(); 
    } 
} 

回答

1

你是否在UI線程之外進行網絡調用?因爲你有NetworkOnMainThreadException ...

如果沒有,請使用AsyncTask。例如:

或者

您可以使用Android的異步HTTP客戶端庫。非常簡單的庫,小尺寸(25kb),易於使用和異步。代碼將如下所示:

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

可用here


否則,你可能要削減你的電話到單獨的調用,並檢查空值

URLConnection urlcon = url.openConnection(); 
urlcon.setReadTimeout(10000); 
InputStream is = urlcon.getInputStream();