java - Android 4.0 及以上版本中的 RSS - AsyncTask

标签 java android exception rss rss-reader

我最近一直在创建一个正在开发的应用程序。该应用程序仅在 ListView 中显示 RSS 提要的内容,其中列表项可单击。它可以在 Android 3.0 及更低版本上运行,但是当我将我的应用程序和设备升级到 4.0 及更高版本后,它就失败了。我可以看到,由于 NetworkOnMainThreadException,我需要使用自定义线程,因此我选择了 AsyncTask。我只是在 XML 中有一个带有 id android:id/list 的 ListView ,我用来加载 feed 的代码如下所示:

//Load RSS news feed
// Initializing instance variables
        headlines = new ArrayList();
        links = new ArrayList();

        try {
            URL url = new URL("http://www.vg.no/rss/create.php?categories=25,10,49,26,23,20,21,12,32,30,34&keywords=85,98,1724,84,476,821,820,512,8317,343&limit=15");

            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(false);
            XmlPullParser xpp = factory.newPullParser();

                // We will get the XML from an input stream
            xpp.setInput(getInputStream(url), "UTF_8");

                /* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
                 * However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
                 * As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
                 * so we should skip the "<title>" tag which is a child of "<channel>" tag,
                 * and take in consideration only "<title>" tag which is a child of "<item>"
                 *
                 * In order to achieve this, we will make use of a boolean variable.
                 */
            boolean insideItem = false;

                // Returns the type of current event: START_TAG, END_TAG, etc..
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                if (eventType == XmlPullParser.START_TAG) {

                    if (xpp.getName().equalsIgnoreCase("item")) {
                        insideItem = true;
                    } else if (xpp.getName().equalsIgnoreCase("title")) {
                        if (insideItem)
                            headlines.add(xpp.nextText()); //extract the headline
                    } else if (xpp.getName().equalsIgnoreCase("link")) {
                        if (insideItem)
                            links.add(xpp.nextText()); //extract the link of article
                    }
                }else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
                    insideItem=false;
                }

                eventType = xpp.next(); //move to next element
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Binding data
        ArrayAdapter adapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, headlines);

        setListAdapter(adapter);
    } catch (RuntimeException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(getApplicationContext(), "Cannot load news, please check internett connection", Toast.LENGTH_LONG).show();
    }

我一直在努力理解它;但是,我无法让它工作。如果有人可以帮助我将所有这些放入 AsyncTask 中,并在 onCreate() 和 onClick() 上调用 RSS 刷新并解释如何操作,那就太好了。

谢谢!

最佳答案

这是一个样板内联 AsyncTask 方法

new AsyncTask<Void, Void, Void>({

//initialize headlines here or outside of here or before this Asynctask
    headlines = new ArrayList();
    links = new ArrayList();

@Override
protected Void doInBackground(Void... params)

 try {
        URL url = new URL("http://www.vg.no/rss/create.php?categories=25,10,49,26,23,20,21,12,32,30,34&keywords=85,98,1724,84,476,821,820,512,8317,343&limit=15");

        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(false);
        XmlPullParser xpp = factory.newPullParser();

            // We will get the XML from an input stream
        xpp.setInput(getInputStream(url), "UTF_8");

            /* We will parse the XML content looking for the "<title>" tag which appears inside the "<item>" tag.
             * However, we should take in consideration that the rss feed name also is enclosed in a "<title>" tag.
             * As we know, every feed begins with these lines: "<channel><title>Feed_Name</title>...."
             * so we should skip the "<title>" tag which is a child of "<channel>" tag,
             * and take in consideration only "<title>" tag which is a child of "<item>"
             *
             * In order to achieve this, we will make use of a boolean variable.
             */
        boolean insideItem = false;

            // Returns the type of current event: START_TAG, END_TAG, etc..
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {

                if (xpp.getName().equalsIgnoreCase("item")) {
                    insideItem = true;
                } else if (xpp.getName().equalsIgnoreCase("title")) {
                    if (insideItem)
                        headlines.add(xpp.nextText()); //extract the headline
                } else if (xpp.getName().equalsIgnoreCase("link")) {
                    if (insideItem)
                        links.add(xpp.nextText()); //extract the link of article
                }
            }else if(eventType==XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("item")){
                insideItem=false;
            }

            eventType = xpp.next(); //move to next element
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected Void onPostExecute() //UI THREAD STUFF , onPostExecute may need an argument, not sure yet though
    ArrayAdapter adapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1, headlines);

    setListAdapter(adapter);
}

}).execute();

祝你好运,你可以在onPreExecute()中放置一个加载进度条

关于java - Android 4.0 及以上版本中的 RSS - AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14526598/

相关文章:

java - 如何计算时间间隔

android - 应用程序在 pclose 上崩溃

java - 想在java中格式化大于20位的数字吗?

java - 下载在 ListView 中重新开始

禁用深度测试时,Java OpenGL 颜色 Material 变暗

java - 将 Office 文档转换为 PDF 或图像的最佳选择是什么

java - 在 Android 上使用 SQLite 时出现 OutOfMemory 异常

java - 使用 eclipse 无法在 java 中解决 PMD 错误

python - 将异常主体存储在变量中

ruby-on-rails-3 - Rails Article.find 1 在遗留数据库上引发 ActiveRecord::StatementInvalid