How do I resolve android.os.NetworkOnMainThreadException?

Asked 2 years ago, Updated 2 years ago, 155 views

When ANDROID.OS.NETWORKONMAINTHREADEXCEPTION occurs, What should I do?

In the below code I got an error when running my Android project for RssReader.

I'm working on a project that reads Rss on Android like the code below The above error occurs.

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

What should I do?

android networkonmainthread thread-exceptions

2022-09-22 21:37

1 Answers

The above exception occurs when you run network operations on the main thread of the application. Therefore, it can be easily solved by using AsyncTask as shown below.

class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {

    private Exception exception;

    //What to run in the background when using AsyncTask
    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;
        }
    }
    //doInBackground is called after the operation
    protected void onPostExecute(RSSFeed feed) {
        // TODO: Check if this.exception has occurred
        // TODO: Properly handle with received feed
    }
}

OnCreate() in MainActivity, when you do new RetrieveFeedTask().execute(urlToRssFeed); AsyncTask is simply called.

Also, you have to add permission to the Android manifest file like the code below to operate normally. <uses-permission android:name="android.permission.INTERNET"/>


2022-09-22 21:37

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.