python小菜 2011-06-14 12:02 采纳率: 0%
浏览 602
已采纳

如何修复 android.os.networksonmainthreadexception?

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?

转载于:https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception

  • 写回答

30条回答 默认 最新

  • 妄徒之命 2011-06-14 12:15
    关注

    This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in 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

    new RetrieveFeedTask().execute(urlToRssFeed);
    

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

    <uses-permission android:name="android.permission.INTERNET"/>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择