When ANDROID.OS.NETWORKONMAINTHREADEXCEPTION occurs, What should I do?
In the below code I got an error when running my Android project for RssReader.
I'm working on a project that reads Rss on Android like the code below The above error occurs.
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();
What should I do?
android networkonmainthread thread-exceptions
The above exception occurs when you run network operations on the main thread of the application. Therefore, it can be easily solved by using AsyncTask as shown below.
class RetrieveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
//What to run in the background when using AsyncTask
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;
}
}
//doInBackground is called after the operation
protected void onPostExecute(RSSFeed feed) {
// TODO: Check if this.exception has occurred
// TODO: Properly handle with received feed
}
}
OnCreate() in MainActivity, when you do new RetrieveFeedTask().execute(urlToRssFeed); AsyncTask is simply called.
Also, you have to add permission to the Android manifest file like the code below to operate normally.
<uses-permission android:name="android.permission.INTERNET"/>
573 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
621 Uncaught (inpromise) Error on Electron: An object could not be cloned
613 GDB gets version error when attempting to debug with the Presense SDK (IDE)
918 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
© 2024 OneMinuteCode. All rights reserved.