2012-11-16 37 views
0

我想要一個RSS Feed顯示在Android應用程序中。基本上,它當然是從XML文件中讀取的。我想要在Android listViewtitledescription中顯示兩個項目。Java/Android中的RSS提要佈局

我想進這樣做:

title 
description 

title 
description 

title 
description 

title 
description 

相反,它是這樣做的:

title 
title 
title 
title 
title 
title 

description 
description 
description 
description 
description 
description 

我能看到爲什麼在此基礎上的代碼是怎樣的,但我想不出如何佈局像實施例編號1

這裏是代碼:

private class RSSHandler extends DefaultHandler { 

    public void startElement(String uri, String localName, String qName, 
      Attributes attrs) throws SAXException { 

     if (localName.equals("item")) { 
      item = true; 
     } 

     if (localName.equalsIgnoreCase("title")) { 
      fTitle = true; 
     } 

     if (localName.equalsIgnoreCase("description")) { 
      fDesc = true; 
     } 

    } 

    public void endElement(String namespaceURI, String localName, 
      String qName) throws SAXException { 

    } 

    public void characters(char[] ch, int start, int length) 
      throws SAXException { 

     if (fTitle) { 
      titleResult = titleResult + (new String(ch, start, length)) 
        + "\t\n\n"; 
      fTitle = false; 
     } 

     if (fDesc) { 
      rssResult = rssResult + (new String(ch, start, length)) 
        + "\t\n\n"; 
      fDesc = false; 
     } 

    } 

} 

回答

1

您正在維護兩個字符串並稍後將它們組合在一起,您應該在構建它們時組合它們。根據你的例子你應該使用這樣的事情:

public void characters(char[] ch, int start, int length) 
     throws SAXException { 

    if (fTitle) { 
     titleResult = titleResult + (new String(ch, start, length)) 
       + "\t\n"; 
     fTitle = false; 
    } 

    if (fDesc) { 
     titleResult = titleResult + (new String(ch, start, length)) 
       + "\t\n\n"; 
     fDesc = false; 
    } 
} 
1

相反,你做到這一點:

if (fTitle) { 
     titleResult = titleResult + (new String(ch, start, length)) 
       + "\t\n\n"; 
     fTitle = false; 
    } 

if (fDesc) { 
     rssResult = rssResult + (new String(ch, start, length)) 
       + "\t\n\n"; 
     fDesc = false; 
    } 

看看你正在撰寫兩個字符串一個有很多頭銜和超視距雷達有很多描述。

儘量讓List<String>並添加你的對象有:

List<String> feeds = new ArrayList<String>(); 
... 
public void characters(char[] ch, int start, int length) 
     throws SAXException { 

    String feed = new String(""); 
    if (fTitle) { 
     feed = new String(ch, start, length) 
       + "\t\n\n"; 
     fTitle = false; 
    } 

    if (fDesc) { 
     feed = feed + (new String(ch, start, length)) 
       + "\t\n\n"; 
     fDesc = false; 
    } 
    feeds.add(feed); 
} 

然後你可以使用打印顯示您的列表:

for(String feed : feeds) { 
    <Use your string> 
    feed.doSometing(); 
} 

但最好的初步實踐,你做一個Feed對象存儲標題和描述,如:

List<Feed> feeds = new ArrayList<Feed>(); 
Feed feed = new Feed(title, description); 
feeds.add(feed); 
for(Feed feed : feeds) { 
    feed.getTitle().doSometing(); 
    feed.getDescription().doSometing(); 
} 

=)