安卓:SAX解析到ListView [英] Android: Sax parsing to a listview

查看:157
本文介绍了安卓:SAX解析到ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是新来的Andr​​oid和Java。我一直在尝试一个简单的RSS阅读器添加到我的一个应用程序。所有我希望它做的是解析来自特定网站RSS源,并采取了标题和出版日期,把这些项目变成ListView和被点击列表项目时,它会打开浏览器以显示包含文章的网页。很容易的吧?我很伤心地说,它已难倒我现在几天了。

First off I'm new to Android and Java.. I have been trying to add a "simple" Rss Reader to an app of mine. All I want it to do is Parse a RSS feed from a specific site and take the Title and published date and put those items into a listview and when a list item is clicked it will open the browser to display the webpage containing the article. Easy enough right? I'm sad to say it has had me stumped for a few days now.

我读过一些教程/例子和我试图修改,以适应我的目的看起来像code:结果
主要活动

I've read a few tutorials/examples and the code that I'm trying to modify to suit my purpose looks like:
Main Activity

public class News extends Activity {

    private final String MY_DEBUG_TAG = "Some NEWS";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
            super.onCreate(icicle);

            /* Create a new TextView to display the parsingresult later. */
            TextView tv = new TextView(this);
            try {
                    /* Create a URL we want to load some xml-data from. */
                    URL url = new URL("http://www.some.com/feed/");

                    /* Get a SAXParser from the SAXPArserFactory. */
                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();

                    /* Get the XMLReader of the SAXParser we created. */
                    XMLReader xr = sp.getXMLReader();
                    /* Create a new ContentHandler and apply it to the XML-Reader*/ 
                    ExampleHandler myExampleHandler = new ExampleHandler();
                    xr.setContentHandler(myExampleHandler);

                    /* Parse the xml-data from our URL. */
                    xr.parse(new InputSource(url.openStream()));
                    /* Parsing has finished. */

                    /* Our ExampleHandler now provides the parsed data to us. */
                    ParsedExampleDataSet parsedExampleDataSet = 
                                                                    myExampleHandler.getParsedData();

                    /* Set the result to be displayed in our GUI. */
                    tv.setText(parsedExampleDataSet.toTitle());

            } catch (Exception e) {
                    /* Display any Error to the GUI. */
                    tv.setText("Error: " + e.getMessage());
                    Log.e(MY_DEBUG_TAG, "NewsQueryError", e);
            }
            /* Display the TextView. */
            this.setContentView(tv);
    }
}

ExampleHandler

ExampleHandler

   public class ExampleHandler extends DefaultHandler{

    // ===========================================================
    // Fields
    // ===========================================================

    private boolean in_entry = false;
    private boolean in_id = false;
    private boolean in_title = false;
    private boolean in_updated = false;
    private boolean in_summary = false;
    private boolean in_link = false;

    private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();




    // ===========================================================
    // Getter & Setter
    // ===========================================================

    public ParsedExampleDataSet getParsedData() {
        return this.myParsedExampleDataSet;
    }

    // ===========================================================
    // Methods
    // ===========================================================
    @Override
    public void startDocument() throws SAXException {
        this.myParsedExampleDataSet = new ParsedExampleDataSet();
    }

    @Override
    public void endDocument() throws SAXException {
            // Nothing to do
    }

    /** Gets be called on opening tags like: 
     * <tag> 
     * Can provide attribute(s), when xml was like:
     * <tag attribute="attributeValue">*/
    @Override
    public void startElement(String namespaceURI, String localName,
                    String qName, Attributes atts) throws SAXException {
            if (localName.equals("entry")) {                    
                    this.in_entry = true;
            }else if (localName.equals("id")) {                 
                    this.in_id = true;
            }else if (localName.equals("title")) {
                    this.in_title = true;
            }else if (localName.equals("updated")){
                    this.in_updated = true;
            }else if (localName.equals("summary")) {
                    this.in_summary = true;
            }else if (localName.equals("link")) {
                    this.in_link = true;
            }
    }

    /** Gets be called on closing tags like: 
     * </tag> */
    @Override
    public void endElement(String namespaceURI, String localName, String qName)
                    throws SAXException {
            if (localName.equals("entry")) {
                    this.in_entry = false;
            }else if (localName.equals("id")) {
                    this.in_id = false;
            }else if (localName.equals("title")) {
                    this.in_title = false;
            }else if (localName.equals("updated")) {
                    this.in_updated = false;
            }else if (localName.equals("summary")) {
                    this.in_summary = false;
            }else if (localName.equals("link")) {
                    this.in_link = false;
            }
    }

    /** Gets be called on the following structure: 
     * <tag>characters</tag> */
    public void characters(char ch[], int start, int length) {
        if(this.in_title){
        myParsedExampleDataSet.setextractedTitle(new String(ch, start, length));
}
}
}

ParsedExampleDataSet

ParsedExampleDataSet

public class ParsedExampleDataSet {
    private String extractedId = null;
    private String extractedTitle = null;
    private String extractedUpdated = null;
    private String extractedSummary = null;
    private String extractedImage = null;
    private int extractedInt = 0;

    public String getextractedId() {
            return extractedId;
    }
    public void setextractedId(String extractedId) {
            this.extractedId = extractedId;
    }

    public String getextractedTitle() {
        return extractedTitle;
    }
    public void setextractedTitle(String extractedTitle) {
        this.extractedTitle = extractedTitle;
    }
    public String getextractedUpdated() {
        return extractedUpdated;
    }
    public void setextractedUpdated(String extractedUpdated) {
        this.extractedUpdated = extractedUpdated;
    }

    public String getextractedSummary() {
        return extractedSummary;
    }
    public void setextractedSummary(String extractedSummary) {
        this.extractedSummary = extractedSummary;
    }



    public String toId(){
            return  this.extractedId;
    }

    public String toTitle(){
        return  this.extractedTitle;
    }

    public String toUpdated(){
        return  this.extractedUpdated;
    }

    public String toSummary(){
        return  this.extractedSummary;
    }
}

现在当然这只是返回在饲料中的最后一项。它是正确解析,因为我可以得到我要单独显示每个元素。我只是无能,如何实现一个listveiw。

Now of course this will just return the last entry in the feed. It is parsing properly as I can get each element that I want to display individually. I'm just clueless as to how to implement a listveiw.

在此先感谢

推荐答案

让我们一步一步来,希望我们可以达到你想要做什么。我已经包含了相关的链接到你需要知道的API文档。

Let's take this step by step and hopefully we could achieve what you want to do. I have included relevant links to the API Documentation that you need to know.


  • 对于ListView控件,DOM可能是一个更简单的选择,因为ListView的是将与结构化列表很好地工作列表上运行。它也更容易学习的人谁新到Android和Java。看看这个 IBM教程XML 基于DOM节实施饲料分析器。下面是$ C $的c您应该关心在这个例子
  • 部分
  • For ListView, DOM is probably a simpler choice since ListView is operating on a list which would work nicely with structured list. It's also easier to learn for someone who new to Android and Java. Look at this IBM tutorial for XML on section "DOM-based implementation of feed parser". Below is the section of the code you should care for in the example


    DocumentBuilder builder = factory.newDocumentBuilder();
    Document dom = builder.parse(this.getInputStream());
    Element root = dom.getDocumentElement();


  • 在这一点上,你拥有的数据为您的ListView 。 ListView的工作原理是服用适配器。适配器是一个负责
    一个。设置初始数据和b。显示每一行应该什么样子。因此这个类是制作的ListView作品
  • 重要
  • 现在,你要创建自己的 BaseAdapter 的扩展,将带你以前得到的根元素。我在这里提供了一个框架类:

    • At this point you have the data for your ListView. ListView works by taking an Adapter. Adapter is the one responsible for a. Setting the initial data and b. Showing how each row should look like. As such this class is important for making ListView works
    • Now you are going to create your own extension of BaseAdapter which will take the root element that you have gotten before. I have provided a skeleton class here:
    • import android.view.View;
      import android.view.ViewGroup;
      import android.widget.BaseAdapter;
      
      public class RSSAdapter extends BaseAdapter {
          Element rootElement;
      
          public RSSAdapter(Element rootElement) {
              this.rootElement = rootElement;
          }
      
          public int getCount() {
              // get the count of children of the root element
              return 0;
          }
      
          public Object getItem(int position) {
              // get the child identified by the position, 
              // this is the important part where you    
              // want to get the right child representing the RSS data that you want to get
              return null;
          }
      
          public long getItemId(int position) {
              return position;
          }
      
          public View getView(int position, View convertView, ViewGroup parent) {
              // implement your view here....
              return null;
          }
      }
      


      • 如果您不熟悉的元素,我建议你看看下面的元素API文档。您需要正确识别的getItem子()函数上述

      • 现在,你就可以实现getView()方法。在这里,您将基本上完成下面的操作

        • 可以访问您想使用getItem()时,你已经实现了子节点

        • 创建为每行一个XML的布局和这里充气它们。如果你不熟悉Android设备上查看,看看查看API文档作为这是要知道一件重要的事情

        • 从子节点提取数据,并将其设置为您相应的视图元素

        • If you are not familiar with Element, I suggest you look at the following Element API Documentation. You would need to correctly identify the child in getItem() function above
        • Now you are ready to implement getView() method. Here you would basically do the following step
          • Get access to the child node that you want using getItem() that you have implemented
          • Create an XML layout for each row and inflate them here. If you are not familiar with Android View, look at View API Documentation as this is an important thing to know
          • Extract the data from the child node and set it to your corresponding View element

          这应该足以让你实现你想要的。如果步骤都不清楚我会进一步澄清。希望这有助于。

          This should be enough for you to implement what you want. I would clarify further if the steps are not clear. Hope this helps.

          这篇关于安卓:SAX解析到ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆