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条)

报告相同问题?

悬赏问题

  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样