Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

java - 如何修复“ android.os.NetworkOnMainThreadException”?(How do I fix 'android.os.NetworkOnMainThreadException'?)

I got an error while running my Android project for RssReader.

(运行RssReader的Android项目时出现错误。)

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?

(如何解决此问题?)

  ask by bejoy george translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This exception is thrown when an application attempts to perform a networking operation on its main thread.

(当应用程序尝试在其主线程上执行联网操作时,将引发此异常。)

Run your code in AsyncTask :

(在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

(在MainActivity.java文件中,您可以在oncreate()方法中添加此行)

new RetrieveFeedTask().execute(urlToRssFeed);

Don't forget to add this to AndroidManifest.xml file:

(不要忘记将其添加到AndroidManifest.xml文件中:)

<uses-permission android:name="android.permission.INTERNET"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...