希望你一切都好:)
我想使用 AsyncTask 来解析 XML。确实,在应用程序启动时,我在网上解析 XML 文件,但我想使用 API 11 及更高版本上的一些可用功能,但我必须将解析放入 AsyncTask 中,我真的不知道该怎么做做这个!
这是我在开始时执行的 onCreate() 方法(类“Main”):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
feeds = DataFeed.getFeeds();
lfa = new ListFeedAdapter(this, feeds);
feedView = ((ListView)findViewById(R.id.listFeed));
feedView.setAdapter(lfa);
feedView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Feed feed = (Feed) feedView.getItemAtPosition(position);
Log.d("Date", ""+getDatePreferedFormat(feed.getPubDate()));
}
});
feedView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
shareIt(position);
return true;
}
});
}
这里是“DataFeed.class”类中的 getFeeds() 方法:
public static ArrayList<Feed> getFeeds(){
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parsor = null;
ArrayList<Feed> feeds = null;
try {
parsor = factory.newSAXParser();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
URL url = null;
try {
url = new URL("http://localhost/feed");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
DefaultHandler handler = new ParserXMLHandler();
try {
// Parsing and get all data
parsor.parse(url.openConnection().getInputStream(), handler);
feeds = ((ParserXMLHandler) handler).getData();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Return arrayList with feeds
return feeds;
}
真的很感谢你的帮助!