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?
Best Solution
NOTE : AsyncTask was deprecated in API level 30.
AsyncTask | Android Developers
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in
AsyncTask
:How to execute the task:
In
MainActivity.java
file you can add this line within youroncreate()
methodDon't forget to add this to
AndroidManifest.xml
file: