當我運行我的android工程時,下邊的代碼中我得到了一個錯誤
URL url= new URL(urlToRssFeed);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader xmlreader=parser.getXMLReader();
RssHandler theRSSHandler=new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is=new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
錯誤是
android.os.NetworkOnMainThreadException
我怎麼能夠改掉這個錯誤?
我的版本是
SDK Platform Android 3.1,API 12, Revision 2 Eclipse SDK - 3.6.2
當一個應用程序試圖在它的主線程執行網絡操作的時候就會拋出這個異常。在AsyncTask中運行代碼:
class RetreiveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
protected RSSFeed doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader xmlreader=parser.getXMLReader();
RssHandler theRSSHandler=new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is=new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(RSSFeed feed) {
}
}
new RetreiveFeedTask().execute(urlToRssFeed);