【问题标题】:RSS Feeder Android AppRSS Feeder Android 应用程序
【发布时间】:2014-04-19 20:19:51
【问题描述】:

我正在为显示 RSS 提要构建 android 应用程序,在一个活动中,我在 EditText 中编写 RSS 链接并单击按钮,然后出现 RSS 提要(新闻)。

当我进入RSS链接并在第一次单击按钮时,新闻正常出现,但我的问题是当我输入新链接并按下按钮时:新链接的新闻出现在旧新闻下(新闻我在 EditText 中输入的第一个链接)。

但我想删除旧新闻并在我按下按钮时显示新链接的 RSS 提要。

有什么想法吗?

提前致谢。

我的代码:

在 MainActivity 中:

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";

    private static String rss_url = "http://www.thehindu.com/news/cities/chennai/chen-health/?service=rss";

    ProgressDialog progressDialog;
    Handler handler = new Handler();

    RSSListView list;
    RSSListAdapter adapter;
    ArrayList<RSSNewsItem> newsItemList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        list = new RSSListView(this);

        adapter = new RSSListAdapter(this);
        list.setAdapter(adapter);
        list.setOnDataSelectionListener(new OnDataSelectionListener() {
            public void onDataSelected(AdapterView parent, View v,
                    int position, long id) {
                RSSNewsItem curItem = (RSSNewsItem) adapter.getItem(position);
                String curTitle = curItem.getTitle();

                Toast.makeText(getApplicationContext(),
                        "Selected : " + curTitle, 1000).show();
            }
        });

        newsItemList = new ArrayList<RSSNewsItem>();
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
        mainLayout.addView(list, params);

        final EditText edit01 = (EditText) findViewById(R.id.edit01);
        edit01.setText(rss_url);

        Button show_btn = (Button) findViewById(R.id.show_btn);
        show_btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                String inputStr = edit01.getText().toString();
                showRSS(inputStr);
            }

        });

    }

    private void showRSS(String urlStr) {
        try {
            progressDialog = ProgressDialog.show(this, "RSS Refresh",
                    "RSS Lodeing..", true, true);

            RefreshThread thread = new RefreshThread(urlStr);
            thread.start();

        } catch (Exception e) {
            Log.e(TAG, "Error", e);
        }
    }

    class RefreshThread extends Thread {
        String urlStr;

        public RefreshThread(String str) {
            urlStr = str;
        }

        public void run() {

            try {
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder builder = builderFactory.newDocumentBuilder();

                URL urlForHttp = new URL(urlStr);

                InputStream instream = getInputStreamUsingHTTP(urlForHttp);
                // parse
                Document document = builder.parse(instream);
                int countItem = processDocument(document);
                Log.d(TAG, countItem + " news item processed.");

                // post for the display of fetched RSS info.
                handler.post(updateRSSRunnable);

            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    }

    public InputStream getInputStreamUsingHTTP(URL url) throws Exception {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);

        int resCode = conn.getResponseCode();
        Log.d(TAG, "Response Code : " + resCode);

        InputStream instream = conn.getInputStream();

        return instream;
    }

    private int processDocument(Document doc) {
        newsItemList.clear();

        Element docEle = doc.getDocumentElement();
        NodeList nodelist = docEle.getElementsByTagName("item");
        int count = 0;
        if ((nodelist != null) && (nodelist.getLength() > 0)) {
            for (int i = 0; i < nodelist.getLength(); i++) {

                RSSNewsItem newsItem = dissectNode(nodelist, i);
                if (newsItem != null) {
                    newsItemList.add(newsItem);
                    count++;
                }
            }
        }

        return count;
    }

    private RSSNewsItem dissectNode(NodeList nodelist, int index) {
        RSSNewsItem newsItem = null;

        try {
            Element entry = (Element) nodelist.item(index);

            Element title = (Element) entry.getElementsByTagName("title").item(
                    0);
            Element link = (Element) entry.getElementsByTagName("link").item(0);
            Element description = (Element) entry.getElementsByTagName(
                    "description").item(0);

            NodeList pubDataNode = entry.getElementsByTagName("pubDate");
            if (pubDataNode == null) {
                pubDataNode = entry.getElementsByTagName("dc:date");
            }
            Element pubDate = (Element) pubDataNode.item(0);

            Element author = (Element) entry.getElementsByTagName("author")
                    .item(0);
            Element category = (Element) entry.getElementsByTagName("category")
                    .item(0);

            String titleValue = null;
            if (title != null) {
                Node firstChild = title.getFirstChild();
                if (firstChild != null) {
                    titleValue = firstChild.getNodeValue();
                }
            }
            String linkValue = null;
            if (link != null) {
                Node firstChild = link.getFirstChild();
                if (firstChild != null) {
                    linkValue = firstChild.getNodeValue();
                }
            }

            String descriptionValue = null;
            if (description != null) {
                Node firstChild = description.getFirstChild();
                if (firstChild != null) {
                    descriptionValue = firstChild.getNodeValue();
                }
            }

            String pubDateValue = null;
            if (pubDate != null) {
                Node firstChild = pubDate.getFirstChild();
                if (firstChild != null) {
                    pubDateValue = firstChild.getNodeValue();
                }
            }

            String authorValue = null;
            if (author != null) {
                Node firstChild = author.getFirstChild();
                if (firstChild != null) {
                    authorValue = firstChild.getNodeValue();
                }
            }

            String categoryValue = null;
            if (category != null) {
                Node firstChild = category.getFirstChild();
                if (firstChild != null) {
                    categoryValue = firstChild.getNodeValue();
                }
            }

            Log.d(TAG, "item node : " + titleValue + ", " + linkValue + ", "
                    + descriptionValue + ", " + pubDateValue + ", "
                    + authorValue + ", " + categoryValue);

            newsItem = new RSSNewsItem(titleValue, linkValue, descriptionValue,
                    pubDateValue, authorValue, categoryValue);

        } catch (DOMException e) {
            e.printStackTrace();
        }

        return newsItem;
    }

    Runnable updateRSSRunnable = new Runnable() {
        public void run() {

            try {

                Resources res = getResources();
                Drawable rssIcon = res.getDrawable(R.drawable.rss_icon);
                for (int i = 0; i < newsItemList.size(); i++) {
                    RSSNewsItem newsItem = (RSSNewsItem) newsItemList.get(i);
                    newsItem.setIcon(rssIcon);
                    adapter.addItem(newsItem);
                }

                adapter.notifyDataSetChanged();

                progressDialog.dismiss();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

【问题讨论】:

    标签: android rss feed


    【解决方案1】:

    您将项目直接添加到 RSSListAdapter (adapter),但您从未删除或清除之前已添加的项目。由于 RSSListAdapter 不受 newsItemList 的支持,因此清除该列表只会阻止旧项目再次添加。

    在添加新项目之前调用adapter.clear(),或者让adapternewsItemList 支持。

    【讨论】:

    • adapter.clear() 不起作用..我怎样才能让适配器得到 newsItemList 的支持??
    • 好吧,它是你的类,但我假设它是ArrayAdapter 的子类,所以只需实现将列表作为参数的构造函数。
    • 我不明白 :(
    • 仍然假设您扩展了ArrayAdapter,您将创建一个构造函数,采用List&lt;RSSNewsItem&gt;(您的newsItemList),然后调用相应的ArrayAdapterconstructor。然后当您清除newItemsList 时,旧项目将从适配器的数据集中删除。只要确保你也打电话给notifyDataSetChanged
    猜你喜欢
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多