我正在尝试组装一个简单的 RSS 阅读器,并在http://www.ibm.com/developerworks/opensource/library/x-android/上找到了代码
为此,我注意到自 Honeycomb 以来您无法从主线程执行网络操作,并且很难将此类包装到工作的 AsyncTask 中:
package tlib.net.rss;
import java.util.ArrayList;
import java.util.List;
import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.util.Xml;
public class SaxFeedParser extends BaseFeedParser {
public SaxFeedParser(String feedUrl) {
super(feedUrl);
}
public List<Message> parse() {
final Message currentMessage = new Message();
RootElement root = new RootElement("rss");
final List<Message> messages = new ArrayList<Message>();
Element channel = root.getChild("channel");
Element item = channel.getChild(ITEM);
item.setEndElementListener(new EndElementListener(){
public void end() {
messages.add(currentMessage.copy());
}
});
item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setTitle(body);
}
});
item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setLink(body);
}
});
item.getChild(DESCRIPTION).setEndTextElementListener(new
EndTextElementListener(){
public void end(String body) {
currentMessage.setDescription(body);
}
});
item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
public void end(String body) {
currentMessage.setDate(body);
}
});
try {
Xml.parse(this.getInputStream(), Xml.Encoding.UTF_8, root.getContentHandler());
} catch (Exception e) {
throw new RuntimeException(e);
}
return messages;
}
}
这段代码还调用了基类:BaseFeedParser,我猜它也必须被包装到 AsyncTask 中。BaseFeedParser 的代码如下所示:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public abstract class BaseFeedParser implements FeedParser {
// names of the XML tags
static final String CHANNEL = "channel";
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";
private 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);
}
}
}
我不知道我是只是愚蠢还是今天过得很糟糕,但我不明白这是怎么发生的。有人可以帮助我和我下午的大脑来完成这项工作吗?
目前我使用:
SaxFeedParser rss = new SaxFeedParser("http://www.androidster.com/android_news.rss");
messages = rss.parse();
for(Message message : messages)
{
tv.appendText(message);
}
要处理流,如果一切都使用 AsyncTask 完成,我该怎么办?
亲切的问候
希亚姆