Wednesday, 31 October 2012

Xml parsing Android



Here is an example for parsing channels from a web service into a listview using xml parser.

json.java

package com.example.json;

import java.util.ArrayList;
import java.util.HashMap;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.os.Bundle;
import android.app.ListActivity;

import android.util.Log;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;


public class Json extends  ListActivity
{
   
   private static String url = "http://www.yupptv.com/mobile/androidxml.aspx";
 
   String[] names;
    // JSON Node names

    private static final String CHANNEL = "channel";
    private static final String NAME = "name";
    private static final String ID = "id";
    private static final String TYPE = "type";
    private static final String LANGUAGE = "language";
    private static final String IMAGE = "image";
    private static final String LINK = "link";
    private static final String BANDWIDTH = "bandwidth";
    private static final String CELLNAPID= "cellnapid";
    private static final String TAG = null;
   
   
   
 
   

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
      
        // Hashmap for ListView
        ArrayList<HashMap<String, String>> channelist = new ArrayList<HashMap<String, String>>();
     
       
        XMLParser parser = new XMLParser();
      
        String xml = parser.getXmlFromUrl(url);// getting XML
      
        Document doc = parser.getDomElement(xml); // getting DOM element
       
        NodeList nl = doc.getElementsByTagName(CHANNEL);
       
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++)
        {
           
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => valuez
            map.put(NAME, parser.getValue(e,NAME ));
            Log.i("name"+ NAME, "created");
            map.put(ID, parser.getValue(e,ID));
            map.put(TYPE,parser.getValue(e,TYPE ));
            map.put(LANGUAGE,parser.getValue(e,LANGUAGE ));
            map.put(IMAGE,parser.getValue(e,IMAGE));
            map.put(LINK,parser.getValue(e,LINK ));
            map.put(BANDWIDTH,parser.getValue(e,BANDWIDTH));
            map.put(CELLNAPID, parser.getValue(e,CELLNAPID ));
           
         
         
             channelist.add(map);    
        
                      
        }
       
            ListAdapter adapter = new SimpleAdapter(this, channelist,
            R.layout.list_item,
            new String[] { NAME, ID,TYPE,LANGUAGE,IMAGE,LINK,BANDWIDTH,CELLNAPID}, new int[] {
                    R.id.name, R.id.id,R.id.type,R.id.language,R.id.image,R.id.link,R.id.bandwidth,R.id.cellnapid });
 
    setListAdapter(adapter);


  
    }
   
  

}



xmlparser.java






package com.example.json;


import java.io.IOException;

import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;
import android.util.Log;

public class XMLParser {
   
    public String getXmlFromUrl(String url) {
        String xml =null ;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);
           
         

        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
           // e.printStackTrace(err);
        }
        // return XML
     
        return xml;
      
    }
   

    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
           
            DocumentBuilder db = dbf.newDocumentBuilder();
         
//            InputSource is = new InputSource();
//                is.setCharacterStream(new StringReader(xml));
              
                doc = db.parse("http://www.yupptv.com/mobile/androidxml.aspx");
               
             
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
        catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
      
                // return DOM
            return doc;
         
    }
    public String getValue(Element item, String str)
    {
        NodeList n = item.getElementsByTagName(str);
       
        return this.getElementValue(n.item(0));
       
    }
   
    public final String getElementValue( Node elem ) {
             Node child;
             if( elem != null){
                 if (elem.hasChildNodes()){
                     for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                         if( child.getNodeType() == Node.TEXT_NODE ){
                             return child.getNodeValue();
                             
                         }
                     }
                 }
             }
             return "";
   
    }

   
}

json.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>
   
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
         />

    <TextView
        android:id="@+id/type"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/link"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/bandwidth "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/cellnapid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       
        android:textAppearance="?android:attr/textAppearanceLarge" />
   
</LinearLayout>


give permission in manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>




Screen shot

No comments:

Post a Comment