How to fix ‘android.os.NetworkOnMainThreadException’ in android | Best practice

Published by inkskull on

How to fix ‘android.os.NetworkOnMainThreadException’ in android | Best practice

This exception is occurred when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask: or Using RxJava or Use co-routines in kotlin

Example below showing the implementation using AsyncTask

class Task 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();
            InputSource is = new InputSource(url.openStream());

            return theRSSHandler.getFeed();
        } catch (Exception e) {
            this.exception = e;

            return null;
        } finally {

    protected void onPostExecute(RSSFeed feed) {
        // TODO: check this.exception
        // TODO: do something with the feed

How to execute the task:

In file you can add this line within your oncreate() method

new Task().execute(urlToRssFeed);

Categories: Android


Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By :