How to fix 'android.os.NetworkOnMainThreadException'?

how to fix anything
how to fix phone
how to fix things
how to fix things around the house
how to fix broken things
how to fix a zipper
how to fix things book
how to fix something

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?

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your 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 is = new InputSource(url.openStream());
            xmlreader.parse(is);

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

            return null;
        } finally {
            is.close();
        }
    }

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

How to execute the task:

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

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>

How to Fix ANYTHING, iFixit is a global community of people helping each other repair things. Let's fix the world, one device at a time. Troubleshoot with experts in the Answers  How To Repair and Restore Windows 10 Method 1: Use Windows Startup Repair. If Windows 10 is unable to boot up and takes you to Method 2: Use Windows Restore. Complete step 1 from the previous method to get to Windows 10's Method 3: Perform a Disk Scan. Your Windows 10 problems may stem from

You should almost always run network operations on a thread or as an asynchronous task.

But it is possible to remove this restriction and you override the default behavior, if you are willing to accept the consequences.

Add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 

In your class,

and

ADD this permission in android manifest.xml file:    

<uses-permission android:name="android.permission.INTERNET"/>

Consequences:

Your app will (in areas of spotty internet connection) become unresponsive and lock up, the user perceives slowness and has to do a force kill, and you risk the activity manager killing your app and telling the user that the app has stopped.

Android has some good tips on good programming practices to design for responsiveness: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

How To FIX YOUR PHONE In SECONDS! (Reacting To Life Hacks , Expert advice on how to repair hardwood floor water damage, hardwood floor gouge repair, repairing a hardwood floor finish, fixing wood flooring scratches, and  iFixit is a global community of people helping each other repair things. Let's fix the world, one device at a time. Troubleshoot with experts in the Answers forum—and build your own how-to guides to share with the world.

I solved this problem using a new Thread.

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 

Repair Manuals for Every Thing, This educator's guide provides articles, videos & other resources to aid in teaching about tools, common home repair projects and vocabulary to students. Help is here! Learn how to do your own repairs and save money! This site is filled with articles written by skilled individuals. You will find step by step How-To, tips and tricks, and general guidance on fixing your stuff.

iFixit: The Free Repair Manual, Learn how to fix your broken appliance yourself, no repairman needed. Select the appliance that is giving you trouble and you'll find information on the common​  Right-click the Taskbar in a blank area, and select Show touch keyboard button. A new icon of a little keyboard will appear next to the clock in the taskbar. Tap it anytime with the mouse cursor to

You cannot perform network I/O on the UI thread on Honeycomb. Technically, it is possible on earlier versions of Android, but it is a really bad idea as it will cause your app to stop responding, and can result in the OS killing your app for being badly behaved. You'll need to run a background process or use AsyncTask to perform your network transaction on a background thread.

There is an article about Painless Threading on the Android developer site which is a good introduction to this, and it will provide you with a much better depth of an answer than can be realistically provided here.

How to Repair, How to Fix (Just About) Everything: More Than 550 Step-by-Step Instructions for Everything from Fixing a Faucet to Removing Mystery Stains to Curing a  How to Fix, computer hardware and software. Computer Repairing Training. Printers Repairing Training and Troubleshooting. Laptop Desktop printer troubleshoot

How to Fix It Yourself, Need to repair your iPhone? Make an appointment at an Apple Store or an Apple Authorized Service Provider. Find out how much it will cost and how long it will  SEE THE REPAIR GUIDE For each problem there is a solution and we have a handful of them! See the video and step-by-step instructions on how to repair your appliance and be prepared to get your hands dirty.

How To Fix A Broken Appliance, Fix.com is a one-stop source for fixing products in and around your home. Millions of quality OEM replacement parts, repair videos, instructions, and same-day shipping available!

How to Fix (Just About) Everything: More Than 550 Step-by-Step , If that doesn't work, we recommend running a Windows troubleshooter for the type of issue you are having. Windows 10: Select the Start button, then select Settings > Update & Security , and then select Troubleshoot. Look through the list for the troubleshooter that addresses your issue.

Comments
  • Read this blog post on the NetworkOnMainThreadException for more information. It explains why this occurs on Android 3.0 and above.
  • To be on rite track first read about the Network Requests in android then i would recommend to study "Volley".
  • 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 :)
  • You need to run internet activities on a thread separate from main (UI) thread
  • "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/…
  • I think it is worth noting here that the code snippet above is supposed to be a subclass (inner class), preferably private. That way when the AsyncTask finishes, you can still manipulate the innards of your class.
  • Actually i did the Same thing as u mentioned above but m facing this error java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
  • This is exactly the wrong answer. I come across this all the time in peoples code, and its annoying to have to fix it all the time. AsyncTask should not be used for network activity, because it's tied to the activity, but not the activity lifecycle. Rotating the device with this task is running will cause an exception and crash your app. Use an IntentService that drops data in the sqlite database instead.
  • Caution, AsyncTask is often used for per activity network operations when it should not be. its lifecycle is not in sync with the activity. For fetching data, you should use an IntentService and the database behind the view.
  • @BrillPappin, FWIW, this Android Developer Guide uses AsyncTask, and takes care of a configuration change.
  • This is a very bad idea. the solution is to avoid network IO on main thread (as the accepted answer shows).
  • With this you only hide your real problem.
  • @TwistedUmbrella The AsyncTask does not add a page of code, it adds 6 lines (class declaration, override annotation, doInBackground declaration, 2 closing brackets and a call to execute()). On the other hand, even a single fetch from a site as you mention brings a significant lag in the UI responsiveness. Don't be lazy.
  • I think this is the perfect solution if you're looking to just run a sample chunk of code to see if something works before implementing the proper AsyncTask. That's why I upvoted this answer, though as all others have said, this should not be done in a production app, only as a quick workaround for a dev test.