0

我在我的 android 应用程序中创建了一个 rss 提要。但是,我不断发生此错误。

这是我的 logcat 错误...

03-12 14:04:04.025: E/RSS ERROR(4808): Error loading RSS Feed Stream >> null //android.os.NetworkOnMainThreadException
03-12 14:04:04.285: I/dalvikvm(4808): threadid=3: reacting to signal 3
03-12 14:04:04.305: I/dalvikvm(4808): Wrote stack traces to '/data/anr/traces.txt'
03-12 14:04:04.335: D/ViewRootImpl(4808): pckname = com.tmm.android.rssreader
03-12 14:04:04.485: D/libEGL(4808): loaded /system/lib/egl/libEGL_mali.so
03-12 14:04:04.525: D/libEGL(4808): loaded /system/lib/egl/libGLESv1_CM_mali.so
03-12 14:04:04.535: D/libEGL(4808): loaded /system/lib/egl/libGLESv2_mali.so
03-12 14:04:04.575: D/OpenGLRenderer(4808): Enabling debug mode 0

任何人都可以帮忙吗?我是 RSS 提要的新手

我不确定代码的哪一部分出现错误,有什么建议吗?

package com.tmm.android.rssreader.util;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;


public class RSSHandler extends DefaultHandler {

    // Feed and Article objects to use for temporary storage
    private Article currentArticle = new Article();
    private List<Article> articleList = new ArrayList<Article>();

    // Number of articles added so far
    private int articlesAdded = 0;

    // Number of articles to download
    private static final int ARTICLES_LIMIT = 15;

    //Current characters being accumulated
    StringBuffer chars = new StringBuffer();

    /* 
     * This method is called everytime a start element is found (an opening XML marker)
     * here we always reset the characters StringBuffer as we are only currently interested
     * in the the text values stored at leaf nodes
     * 
     * (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
     */
    public void startElement(String uri, String localName, String qName, Attributes atts) {
        chars = new StringBuffer();
    }

    /* 
     * This method is called everytime an end element is found (a closing XML marker)
     * here we check what element is being closed, if it is a relevant leaf node that we are
     * checking, such as Title, then we get the characters we have accumulated in the StringBuffer
     * and set the current Article's title to the value
     * 
     * If this is closing the "Item", it means it is the end of the article, so we add that to the list
     * and then reset our Article object for the next one on the stream
     * 
     * 
     * (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
     */
    public void endElement(String uri, String localName, String qName) throws SAXException {

        if (localName.equalsIgnoreCase("title"))
        {
            Log.d("LOGGING RSS XML", "Setting article title: " + chars.toString());
            currentArticle.setTitle(chars.toString());

        }
        else if (localName.equalsIgnoreCase("description"))
        {
            Log.d("LOGGING RSS XML", "Setting article description: " + chars.toString());
            currentArticle.setDescription(chars.toString());
        }
        else if (localName.equalsIgnoreCase("pubDate"))
        {
            Log.d("LOGGING RSS XML", "Setting article published date: " + chars.toString());
            currentArticle.setPubDate(chars.toString());
        }
        else if (localName.equalsIgnoreCase("encoded"))
        {
            Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
            currentArticle.setEncodedContent(chars.toString());
        }
        else if (localName.equalsIgnoreCase("item"))
        {

        }
        else if (localName.equalsIgnoreCase("link"))
        {
            try {
                Log.d("LOGGING RSS XML", "Setting article link url: " + chars.toString());
                currentArticle.setUrl(new URL(chars.toString()));
            } catch (MalformedURLException e) {
                Log.e("RSA Error", e.getMessage());
            }

        }

        // Check if looking for article, and if article is complete
        if (localName.equalsIgnoreCase("item")) {

            articleList.add(currentArticle);

            currentArticle = new Article();

            // Lets check if we've hit our limit on number of articles
            articlesAdded++;
            if (articlesAdded >= ARTICLES_LIMIT)
            {
                throw new SAXException();
            }
        }
    }


    /* 
     * This method is called when characters are found in between XML markers, however, there is no
     * guarante that this will be called at the end of the node, or that it will be called only once
     * , so we just accumulate these and then deal with them in endElement() to be sure we have all the
     * text
     * 
     * (non-Javadoc)
     * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
     */
    public void characters(char ch[], int start, int length) {
        chars.append(new String(ch, start, length));
    }

    /**
     * This is the entry point to the parser and creates the feed to be parsed
     * 
     * @param feedUrl
     * @return
     */
    public List<Article> getLatestArticles(String feedUrl) {
        URL url = null;
        try {

            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            url = new URL(feedUrl);

            xr.setContentHandler(this);
            xr.parse(new InputSource(url.openStream()));


        } catch (IOException e) {
            Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
        } catch (SAXException e) {
            Log.e("RSS Handler SAX", e.toString());
        } catch (ParserConfigurationException e) {
            Log.e("RSS Handler Parser Config", e.toString());
        }

        return articleList;
    }

}

用于重新编码的 RSS 阅读器的新 LOGCAT 日志

03-12 16:01:13.882: W/System.err(5792): java.net.UnknownHostException: Unable to resolve host "www.cnn.com": No address associated with hostname
03-12 16:01:13.882: W/System.err(5792):     at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
03-12 16:01:13.912: W/System.err(5792):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-12 16:01:13.912: W/System.err(5792):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
03-12 16:01:13.912: W/System.err(5792):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
03-12 16:01:13.922: W/System.err(5792):     at java.net.URL.openStream(URL.java:462)
03-12 16:01:13.922: W/System.err(5792):     at com.exercise.AndroidRssReader.AndroidRssReader$MyTask.doInBackground(AndroidRssReader.java:43)
03-12 16:01:13.922: W/System.err(5792):     at com.exercise.AndroidRssReader.AndroidRssReader$MyTask.doInBackground(AndroidRssReader.java:1)
03-12 16:01:13.922: W/System.err(5792):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
03-12 16:01:13.922: W/System.err(5792):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-12 16:01:13.922: W/System.err(5792):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-12 16:01:13.932: W/System.err(5792):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-12 16:01:13.932: W/System.err(5792):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-12 16:01:13.932: W/System.err(5792):     at java.lang.Thread.run(Thread.java:856)
03-12 16:01:13.932: W/System.err(5792): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
03-12 16:01:13.952: W/System.err(5792):     at libcore.io.Posix.getaddrinfo(Native Method)
03-12 16:01:13.952: W/System.err(5792):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
03-12 16:01:13.952: W/System.err(5792):     at java.net.InetAddress.lookupHostByName(InetAddress.java:411)
03-12 16:01:13.962: W/System.err(5792):     ... 22 more
4

1 回答 1

0
Error loading RSS Feed Stream >> null //android.os.NetworkOnMainThreadException

这意味着您在 UI 线程中调用您的 xml 解析。xml 解析本身通过url.openStream()in获取数据getLatestArticles()。使用 AsyncTask 解析您的 xml 并在完成后发布结果。

于 2013-03-12T15:22:45.677 回答