Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
bejoy george Avatar asked Jun 14 '11 12:06

bejoy george


People also ask

What is NetworkOnMainThreadException?

android.os.NetworkOnMainThreadException. The exception that is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher.

How do I turn on strict mode on Android?

Go to Settings > Developer options. Tap Advanced > Strict mode enabled.


2 Answers

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:

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"/> 
like image 177
Michael Spector Avatar answered Sep 23 '22 15:09

Michael Spector


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 the 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: NetworkOnMainThreadException | Android Developers

like image 41
user1169115 Avatar answered Sep 22 '22 15:09

user1169115