Android XML讀寫(三)
消息基本上是相當(dāng)直觀的。通過允許日期和鏈接作為簡單的對象被訪問,同時將它們表示為較強(qiáng)類型的對象(de >java.util.Datede > 和 de >java.net.URLde >),它隱藏了一些內(nèi)部狀態(tài)。它是一個典型的 Value Object,因此它基于其內(nèi)部狀態(tài)實(shí)現(xiàn)了 de >equals()de > 和 de >hashCode()de >。它還實(shí)現(xiàn)了 de >Comparablede > 接口,因此您可以使用它進(jìn)行排序(按日期)。在實(shí)踐中,提要中的數(shù)據(jù)始終是有序的,因?yàn)闆]有必要再進(jìn)行排序。
每個解析器實(shí)現(xiàn)都需要提供一個 URL 給 Androidster 提要,并使用它打開一個到 Androidster 站點(diǎn)的 HTTP 連接。這一常見行為自然是在 Java 代碼中建模,我們使用了一個抽象基類,所示。
基本提要解析器類
java代碼:
- public abstract class BaseFeedParser implements FeedParser {
 - // names of the XML tags
 - static final String PUB_DATE = "pubDate";
 - static final String DESCRIPTION = "description";
 - static final String LINK = "link";
 - static final String TITLE = "title";
 - static final String ITEM = "item";
 - final URL feedUrl;
 - protected BaseFeedParser(String feedUrl){
 - try {
 - this.feedUrl = new URL(feedUrl);
 - } catch (MalformedURLException e) {
 - throw new RuntimeException(e);
 - }
 - }
 - protected InputStream getInputStream() {
 - try {
 - return feedUrl.openConnection().getInputStream();
 - } catch (IOException e) {
 - throw new RuntimeException(e);
 - }
 - }
 - }
 
基類存儲 de >feedUrlde > 并使用它打開了一個 de >java.io.InputStreamde >。如果出現(xiàn)任何差錯,它會拋出一個 de >RuntimeExceptionde >,造成應(yīng)用程序出現(xiàn)故障?;愡€為標(biāo)記的名稱定義了一些簡單的常量。顯示了提要中的一些示例內(nèi)容,以便于您理解這些標(biāo)記的重要性。
示例 XML 提要
java代碼:
- < ?xml version="1.0" encoding="UTF-8"? >
 - < !-- generator="FeedCreator 1.7.2" -- >
 - < rss version="2.0" >
 - < channel >
 - < title >android_news< /title >
 - < description >android_news< /description >
 - < link >< /link >
 - < lastBuildDate >Sun, 19 Apr 2009 19:43:45 +0100< /lastBuildDate >
 - < generator >FeedCreator 1.7.2< /generator >
 - < item >
 - < title >Samsung S8000 to Run Android, Play DivX, Take Over the World< /title >
 - < link >< /link >
 - < description >More details have emerged on the first Samsung handset
 - to run Android. A yet-to-be announced phone called the S8000 is being
 - reported ...< /description >
 - < pubDate >Thu, 16 Apr 2009 07:18:51 +0100< /pubDate >
 - < /item >
 - < item >
 - < title >Android Cupcake Update on the Horizon< /title >
 - < link >< /link >
 - < description >After months of discovery and hearsay, the Android
 - build that we have all been waiting for is about to finally make it
 - out ...< /description >
 - < pubDate >Tue, 14 Apr 2009 04:13:21 +0100< /pubDate >
 - < /item >
 - < /channel >
 - < /rss >
 















 
 
 
 
 
 
 