Android:RSS Parser

[Fuente: http://devtuts.mobi/Android:RSS_Parser]

Introduccion

En este tuto, intentaremos mostrar como leer un RSS en Android. Pasaremos por encima sin ir a los detalles.

El ejemplo intenta imprimir los titulos de las noticias proporcionados por http://news.google.fr/?output=rss.

Para mostrarlo , simplemente utilizamos una lista.

Creamos un nuevo proyecto, con un ListActivity. Podemos añadir e inicializar atributos para la url del feed y la lista:

package com.jes.rssparser;

import java.util.ArrayList;

import android.app.ListActivity;
import android.os.Bundle;

public class RSSParserActivity extends ListActivity {
	private final String feeds = "http://news.google.fr/?output=rss";
	private ArrayList<String> list;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		list = new ArrayList<String>();
	}
}

Utilizaremos los objetos RootElement y Element para definir la estructura de nuestro feeds. Es muy simple, solo para indicar quien es el padre/hijo de quien:

		RootElement root = new RootElement("rss");
		Element itemlist = root.getChild("channel");
		Element item =  itemlist.getChild("item");

Los elementos item corresponden a cada sección del article. Cada item tiene a su vez varios hijos: titulo, link, descripcion, etc. Por ejemplo sacaremos solo el titulo pero es lo mismo para las otras tags.

Para recuperar los contenidos de la tag title, utilizaremos el método setEndTextElementListener y definiremos un listener:

		item.getChild("title").setEndTextElementListener(
				new EndTextElementListener() {
					public void end(String body) {
						list.add(body);
					}
				});
“body” es el contenido que buscamos, asi que lo añado a mi lista. Finalmente, debemos abrir la conexion, recuperar el contenido parsear el rss:
		try {
			url = new URL(feeds);
			InputStream input = url.openConnection().getInputStream();
			Xml.parse(input, Xml.Encoding.UTF_8, root.getContentHandler());
		} catch (Exception e) {
			Log.e("RSSParser", e.toString());
		}

For details, we instantiate a URL, then start the connection with openconnection(). Data are retrieved with getInputStream (), which is placed in the variable input. Xml.parse() parses the variable input, with the structure that we have stated previously, in a UTF-8 encoding.

That’s all! It remains to link the variable list with the ListView that is showing. Finally, we get the following code:

  1. public class Main extends ListActivity {
  2. private final String feeds = “http://news.google.fr/?output=rss”;
  3. private URL url;
  4. private ArrayList<String> list;
  5. /** Called when the activity is first created. */
  6. @Override
  7. public void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. list = new ArrayList<String>();
  10. RootElement root = new RootElement(“rss”);
  11. Element itemlist = root.getChild(“channel”);
  12. Element item =  itemlist.getChild(“item”);
  13. item.getChild(“title”).setEndTextElementListener(new EndTextElementListener(){
  14. public void end(String body) {
  15. list.add(body);
  16. }
  17. });
  18. try {
  19. url = new URL(feeds);
  20. InputStream input = url.openConnection().getInputStream();
  21. Xml.parse(input, Xml.Encoding.UTF_8, root.getContentHandler());
  22. } catch (Exception e) {
  23. Log.e(“RSSParser”,e.toString());
  24. }
  25. setListAdapter(new ArrayAdapter<String>(this, R.layout.item, list));
  26. }
  27. }

Note

Remember that RSS is an XML file. So you know also parse an XML file!