Android SAXParser не может получить данные в списке - PullRequest
1 голос
/ 02 декабря 2011

Мне нужно создать просмотр списка, который содержит данные, проанализированные из файла XML с моего сервера. Я сделал класс Myhandler для обработки проанализированных данных и myadapter для обработки списка, но список просто пустой, я думаю, что с процессом разбора что-то не так, может кто-нибудь мне помочь? ТНХ

showlist.java

public class Showlist extends ListActivity
{

  private List<Episode> li=new ArrayList<Episode>();

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    /* 设定layout为newslist.xml */
    setContentView(R.layout.showlist);   

    Intent intent=this.getIntent();
    Bundle bunde = intent.getExtras();

    String path = bunde.getString("path");
    String title = bunde.getString("cname");
    String dblink = bunde.getString("dblink");

    Bundle bunde2= new Bundle();
    bunde2.putString("dblink",dblink);

    li=getRss(path);


    setListAdapter(new MyAdapter(this,li));

  }


  @Override
  protected void onListItemClick(ListView l,View v,int position,
                                 long id)
  {

    Episode ed=(Episode)li.get(position);

    Intent intent = new Intent();
    intent.setClass(Showlist.this,Tvs.class);

    Bundle bunde = new Bundle();
    bunde.putString("title",ed.getname());
    bunde.putString("link",ed.getLink());
    bunde.putString("dblink",ed.getdoubanlink());
    bunde.putString("pubdate",ed.getpubdate());

    intent.putExtras(bunde);

    startActivity(intent);
  }

  /* 剖析XML的method */
  private List<Episode> getRss(String path)
  {
    List<Episode> data=new ArrayList<Episode>();
    URL url = null;     
    try
    {  
      url = new URL(path);

      SAXParserFactory spf = SAXParserFactory.newInstance(); 
      SAXParser sp = spf.newSAXParser(); 

      XMLReader xr = sp.getXMLReader(); 

      MyHandler myExampleHandler = new MyHandler(); 
      xr.setContentHandler(myExampleHandler);     

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

      data =myExampleHandler.getParsedData(); 
    }
    catch (Exception e)
    { 

    }
    return data;
  }
}

MyHandler.java

public class MyHandler extends DefaultHandler
{ 
  /* 变量声明 */
  private boolean in_episode = false;
  private boolean in_name = false;
  private boolean in_link = false;
  private boolean in_desc = false;
  private boolean in_date = false;
  private boolean in_mainTitle = false;
  private List<Episode> li;
  private Episode episodes;
  private String title="";
  private StringBuffer buf=new StringBuffer();

  /* 将转换成List<News>的XML数据回传 */
  public List<Episode> getParsedData()
  { 
    return li; 
  }
  /* 将解析出的RSS title回传 */
  public String getRssTitle()
  { 
    return title; 
  }
  /* XML文件开始解析时调用此method */
  @Override 
  public void startDocument() throws SAXException
  { 
    li = new ArrayList<Episode>(); 
  } 
  /* XML文件结束解析时调用此method */
  @Override 
  public void endDocument() throws SAXException
  {
  } 
  /* 解析到Element的开头时调用此method */
  @Override 
  public void startElement(String namespaceURI, String localName, 
               String qName, Attributes atts) throws SAXException
  { 
    if (localName.equals("episode"))
    { 
      this.in_episode = true;
      /* 解析到item的开头时new一个News对象 */
      episodes=new Episode();
    }
    else if (localName.equals("title"))
    { 
      if(this.in_episode)
      {
        this.in_name = true;
      }
      else
      {
        this.in_mainTitle = true;
      }
    }
    else if (localName.equals("link"))
    { 
      if(this.in_episode)
      {
        this.in_link = true;
      }
    }
    else if (localName.equals("desc"))
    { 
      if(this.in_episode)
      {
        this.in_desc = true;
      }
    }
    else if (localName.equals("pubDate"))
    { 
      if(this.in_episode)
      {
        this.in_date = true;
      }
    } 
  }
  /* 解析到Element的结尾时调用此method */
  @Override 
  public void endElement(String namespaceURI, String localName,
                         String qName) throws SAXException
  { 
    if (localName.equals("episode"))
    { 
      this.in_episode = false;
      /* 解析到item的结尾时将News对象写入List中 */
      li.add(episodes);
    }
    else if (localName.equals("title"))
    { 
      if(this.in_episode)
      {
        /* 设定News对象的title */
        episodes.setname(buf.toString().trim());
        buf.setLength(0);
        this.in_name = false;
      }
      else
      {
        /* 设定RSS的title */
        title=buf.toString().trim();
        buf.setLength(0);
        this.in_mainTitle = false;
      }
    }
    else if (localName.equals("link"))
    { 
      if(this.in_episode)
      {
        /* 设定News对象的link */
        episodes.setLink(buf.toString().trim());
        buf.setLength(0);
        this.in_link = false;
      }
    }
    else if (localName.equals("description"))
    { 
      if(in_episode)
      {
        /* 设定News对象的description */
        episodes.setdoubanlink(buf.toString().trim());
        buf.setLength(0);
        this.in_desc = false;
      }
    }
    else if (localName.equals("pubDate"))
    { 
      if(in_episode)
      {
        /* 设定News对象的pubDate */
        episodes.setpubdate(buf.toString().trim());
        buf.setLength(0);
        this.in_date = false;
      }
    } 
  } 
  /* 取得Element的开头结尾中间夹的字符串 */
  @Override 
  public void characters(char ch[], int start, int length)
  { 
    if(this.in_episode||this.in_mainTitle)
    {
      /* 将char[]加入StringBuffer */
      buf.append(ch,start,length);
    }
  } 
}

MyAdapter.java

public class MyAdapter extends BaseAdapter
{
  /* 变量声明  */
  private LayoutInflater mInflater;
  private List<News> items;

  /* MyAdapter的建构子,传入两个参数  */  
  public MyAdapter(Context context,List<News> it)
  {
    /* 参数初始化 */
    mInflater = LayoutInflater.from(context);
    items = it;
  }

  /* 因继承BaseAdapter,需重写以下method */
  @Override
  public int getCount()
  {
    return items.size();
  }

  @Override
  public Object getItem(int position)
  {
    return items.get(position);
  }

  @Override
  public long getItemId(int position)
  {
    return position;
  }

  @Override
  public View getView(int position,View convertView,ViewGroup par)
  {
    ViewHolder holder;

    if(convertView == null)
    {
      /* 使用自定义的news_row作为Layout */
      convertView = mInflater.inflate(R.layout.news_row, null);
      /* 初始化holder的text与icon */
      holder = new ViewHolder();
      holder.text = (TextView) convertView.findViewById(R.id.text);      
      convertView.setTag(holder);
    }
    else
    {
      holder = (ViewHolder) convertView.getTag();
    }
    News tmpN=(News)items.get(position);
    holder.text.setText(tmpN.getTitle());

    return convertView;
  }

  /* class ViewHolder */
  private class ViewHolder
  {
    TextView text;
  }
}

Мой XML-файл

<?xml version="1.0" encoding="UTF-8"?>

<episode id="1">
  <name>11</name>
  <link>http://tv.sohu.com/20100907/n274763276.shtml</link>
  <desc>22</desc>

</episode>

<episode id="2">
  <name>11</name>
  <link>http://tv.sohu.com/20100907/n274763308.shtml</link>
  <desc>22</desc>

</episode>


<episode id="3">
  <name>11</name>
  <link>http://tv.sohu.com/20100907/n274763337.shtml</link>
  <desc>22</desc>

</episode>

Episode.java

public class Episode { 
      /* News的四个变数 */
      private String _name="";
      private String _link="";
      private String _doubanlink="";
      private String _pubdate="";
      private String _item="";

      public String getitem()
      {
          return _item;
      }
      public String getname()
      { 
        return _name; 
      } 
      public String getLink()
      { 
        return _link; 
      }
      public String getdoubanlink()
      { 
        return _doubanlink; 
      } 
      public String getpubdate()
      { 
        return _pubdate; 
      }

      public void setname(String name)
      { 
        _name=name; 
      } 
      public void setLink(String link)
      { 
        _link=link; 
      }
      public void setdoubanlink(String doubanlink)
      { 
        _doubanlink=doubanlink; 
      } 
      public void setpubdate(String pubdate)
      { 
        _pubdate=pubdate; 
      }
    public void setItem(String item) {
        // TODO Auto-generated method stub
        _item=item;
    }
    }
...