Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.io.File;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import android.util.Log;

public class Main {
    public static List<Map<String, String>> ReadPlaylistItemsFromFile(String path, String filename) {

        List<Map<String, String>> results = new ArrayList<Map<String, String>>();

        try {
            File fXmlFile = new File(path, filename);
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            Document doc = dBuilder.parse(fXmlFile);
            doc.getDocumentElement().normalize();

            NodeList songList = doc.getElementsByTagName("song");
            Log.d("ReadItemsFromFile", "List Length: " + songList.getLength());

            for (int i = 0; i < songList.getLength(); i++) {

                Node nNode = songList.item(i);
                if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element eElement = (Element) nNode;

                    HashMap<String, String> mapElement = new HashMap<String, String>();

                    mapElement.put("name", eElement.getElementsByTagName("name").item(0).getTextContent());
                    mapElement.put("artist", eElement.getElementsByTagName("artist").item(0).getTextContent());
                    mapElement.put("startTime",
                            eElement.getElementsByTagName("startTime").item(0).getTextContent());
                    mapElement.put("url", eElement.getElementsByTagName("url").item(0).getTextContent());

                    results.add(mapElement);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return results;

    }
}