谁还没个明天 2011-06-14 12:02 采纳率: 50%
浏览 409
已采纳

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

  • 写回答

29条回答 默认 最新

  • 斗士狗 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"/>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(28条)

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用