Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to 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?
by

2 Answers

RoliMishra
We can solve 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();
Sonali7
There are two ways of solving this Problem.

1. Don't write network call in Main UI Thread, Use Async Task for that.

2. Write below code into your MainActivity file after setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}


The below import statement should be added in the java file.
import android.os.StrictMode;

Login / Signup to Answer the Question.