I want an app that will periodically check a websites rss. And only download the image from the latest article to the sd card. How could i do this. Can you give me some code or a place to lea开发者_StackOverflow社区rn this.
It's dangerous to go alone - take this. This is simple xml parser that adds parsed items to ArrayList. You can use those items later, in some adapter, for example.
Just modify this code to fit your feed. Usage is simple - readRss(1);
read only first item in feed. About how to download image to SD card - there is plenty examples around.
private XmlPullParserFactory factory = null;
private XmlPullParser xpp = null;
private ArrayList<String> newsId;
private ArrayList<String> newsTitle;
private ArrayList<String> newsDescription;
private ArrayList<String> newsImage;
private boolean connect() {
try {
if (xpp == null) {
URL url = new URL(feedString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
xpp = factory.newPullParser();
xpp.setInput(in, "UTF-8");
}
}
return true;
} catch (XmlPullParserException xe) {
Log.e("RssReader", "Connection", xe);
return false;
} catch (IOException eio) {
Log.e("RssReader", "Connection", eio);
return false;
}
}
private void readRss(int itemsToRead) {
boolean insideItem = false;
boolean insideTitle = false;
boolean insideImage = false;
boolean insideDescription = false;
boolean insideId = false;
try {
if (connect()) {
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT
&& itemsToRead >= 0) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) { //news tag
insideItem = true;
} else if (insideItem
&& xpp.getName().equalsIgnoreCase("original")) {
insideImage = true;
} else if (insideItem
&& xpp.getName()
.equalsIgnoreCase("description")) {
insideDescription = true;
} else if (insideItem
&& xpp.getName().equalsIgnoreCase("id")) {
insideId = true;
}
} else if (eventType == XmlPullParser.END_TAG) {
if (xpp.getName().equalsIgnoreCase("item")) {
insideItem = false;
--itemsToRead;
}
} else if (eventType == XmlPullParser.TEXT && insideItem) {
if (xpp.getText() != null) {
if (insideTitle) {
newsTitle.add(xpp.getText());
insideTitle = false;
} else if (insideImage) {
newsImage.add(xpp.getText());
insideImage = false;
} else if (insideDescription) {
newsDescription.add(xpp.getText());
insideDescription = false;
} else if (insideId) {
newsId.add(xpp.getText());
insideId = false;
}
}
}
eventType = xpp.next();
}
}
} catch (XmlPullParserException e) {
Log.e("RssReader", "Connection", e);
} catch (IOException e) {
Log.e("RssReader", "Connection", e);
}
}
精彩评论