How can I fix ‘android.os.NetworkOnMainThreadException’?

I got an error while running my Android project for 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 is = new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();

And it shows the below error:

android.os.NetworkOnMainThreadException

How can I fix this issue?

  • 139

    Read this blog post on the NetworkOnMainThreadException for more information. It explains why this occurs on Android 3.0 and above.

    – 

  • 6

    To be on rite track first read about the Network Requests in android then i would recommend to study “Volley”.

    – 

  • 3

    There are many alternative libraries that solve this issue. Many are listed at the bottom of this page. If you got more, we take them 🙂

    – 

  • “Due to a bug in previous versions of Android, the system did not flag writing to a TCP socket on the main thread as a strict-mode violation. Android 7.0 fixes this bug. Apps that exhibit this behavior now throw an android.os.NetworkOnMainThreadException.” – So some of us haven’t hit this until recently! developer.android.com/about/versions/nougat/…

    – 

Leave a Comment