networkonmainthread - How do I fix android.os.NetworkOnMainThreadException? -
i got error while running android project rssreader.
code:
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 = new inputsource(url.openstream()); xmlreader.parse(is); return thersshandler.getfeed();
and shows below error:
android.os.networkonmainthreadexception
how can fix issue?
this exception thrown when application attempts perform networking operation on main thread. run code in asynctask
:
class retrievefeedtask 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 = new inputsource(url.openstream()); xmlreader.parse(is); return thersshandler.getfeed(); } catch (exception e) { this.exception = e; return null; } } protected void onpostexecute(rssfeed feed) { // todo: check this.exception // todo: feed } }
how execute task:
in mainactivity.java
file can add line within oncreate()
method
new retrievefeedtask().execute(urltorssfeed);
don't forget add androidmanifest.xml
file:
<uses-permission android:name="android.permission.internet"/>
Comments
Post a Comment