venerdì 29 giugno 2012

Leggere un file xml e creare una lista di HashMap di stringhe ordinata alfabeticamente

A partire da un semplice xml che raggruppa libri posso leggerlo e creare una lista di HashMap di libri ordinati per nome.
L'oggetto utilizzato per la lettura del xml in questo esempio è XmlResourceParser e il record utilizza attributi del xml per la memorizzazione dei dati.
Ovviamente si può cambiare l'ordinamento per prezzo o autore.
Di seguito il file xml e il metodo che ritorna la lista di libri.
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <book name="First book" author="E.P." price="9.5"/>
    <book name="Second book" author="A.D." price="12.80"/>
    <book name="Third book" author="F.R." price="14"/>
</resources>
private final static String NAME = "name";
private final static String AUTHOR = "author";
private final static String PRICE = "price";

//...

private List<? extends Map<String,?>> createList() {
    ArrayList<Map<String,String>> lista = new ArrayList<Map<String,String>>();
    //books.xml ad esempio è il file nella directory res/xml del progetto
    XmlResourceParser xrp = getResources().getXml(R.xml.books);
    String author = "";
    String price = "";
    String name ="";
    try{
        xrp.next();  
        int eventType = xrp.getEventType();
   
        while (eventType != XmlResourceParser.END_DOCUMENT) {
            if(eventType == XmlPullParser.START_TAG) {
                String strBook = xrp.getName();
                if (strBook.equals("book")) {
                    name = xrp.getAttributeValue(null, "name");
                    author = xrp.getAttributeValue(null, "author");
                    price = xrp.getAttributeValue(null, "price");
                    Map<String,String> data = new HashMap<String,String>();
                    data.put(NAME,name);
                    data.put(AUTHOR,author);
                    data.put(PRICE,price);
                    lista.add(data);
                }      
            }
            eventType = xrp.next(); 
        }
    } 
    catch (XmlPullParserException e) {   
        } 
    catch (IOException e) {  
    } 
    finally {    
        xrp.close(); 
    }
    //Ordinamento per nome
    Collections.sort(lista, sDisplayNameComparator);    
    return lista;
} 
    
private final static Comparator<Map> sDisplayNameComparator =
 new Comparator<Map>() {     
    private final Collator collator = Collator.getInstance();  
    public int compare(Map map1, Map map2) {       
        return collator.compare(map1.get(NAME), map2.get(NAME)); 
    }   
 };