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?
Use this in Your Activity
New
Thread
and AsyncTask solutions have been explained already.AsyncTask
should ideally be used for short operations. NormalThread
is not preferable for Android.Have a look at alternate solution using HandlerThread and Handler
HandlerThread
Handler:
Solution:
Create
HandlerThread
Call
start()
onHandlerThread
Create
Handler
by gettingLooper
fromHanlerThread
Embed your Network operation related code in
Runnable
objectSubmit
Runnable
task toHandler
Sample code snippet, which address
NetworkOnMainThreadException
Pros of using this approach:
Thread/AsyncTask
for each network operation is expensive. TheThread/AsyncTask
will be destroyed and re-created for next Network operations. But withHandler
andHandlerThread
approach, you can submit many network operations (as Runnable tasks) to singleHandlerThread
by usingHandler
.On Android, network operations cannot be run on the main thread. You can use Thread, AsyncTask (short-running tasks), Service (long-running tasks) to do network operations.
Accessing network resources from the main (UI) thread cause this exception. Use a separate thread or AsyncTask for accessing a network resource to avoid this problem.
This works. Just made Dr.Luiji's answer a little simpler.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads.
The error is the SDK warning!