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?
Put your code inside:
Or:
Using Android Annotations is an option. It will allow you to simply run any method in a background thread:
Note, that although it provides benefits of simplicity and readability, it has its disadvantages.
For me it was this:
The device I was testing my app on was 4.1.2 which is SDK Version 16!
Make the sure the target version is the same as your Android Target Library. If you are unsure what your target library is, right click your Project -> Build Path -> Android, and it should be the one that is ticked.
Also, as others have mentioned, include the correct permissions to access the Internet:
You are able to move a part of your code into another thread to offload the
main thread
and avoid getting ANR, NetworkOnMainThreadException, IllegalStateException(e.g. Cannot access database on the main thread since it may potentially lock the UI for a long period of time).There are some approaches that you should choose depends on the situation
Java Thread or Android HandlerThread
AsyncTask
Thread pool implementation ThreadPoolExecutor, ScheduledThreadPoolExecutor...
FutureTask
AsyncTaskLoaders
IntentService
JobScheduler
RxJava
Coroutines (Kotlin)
Read more here, here, here, here
Just to spell out something explicitly:
The main thread is basically the UI thread.
So saying that you cannot do networking operations in the main thread means you cannot do networking operations in the UI thread, which means you cannot do networking operations in a
*runOnUiThread(new Runnable() { ... }*
block inside some other thread, either.(I just had a long head-scratching moment trying to figure out why I was getting that error somewhere other than my main thread. This was why; this thread helped; and hopefully this comment will help someone else.)
This exception occurs due to any heavy task performed on the main thread if that performing task takes too much time.
To avoid this, we can handle it using threads or executers