撒拉嘿哟木头 2011-06-14 12:02 采纳率: 100%
浏览 432
已采纳

如何修复 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条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作