Skip to main content

Simple Code of DOM Parsing and display result in listview

Hi friends, this is the simplest way of DOM parsing and display result in listview.First its necessary to know that  DOM extends for Document Object Model. As you know that , in XML parsing we will have to create three classes.The first class that should be created when you created the project will be your activity. In this activity, all the data retrieved will be used and displayed to the screen. The second class required will be the handler, in this class all the extracting and setting of data will be done. The third class will contain all the getters and setters that we need to set the data and retrieve it.But here i have added and more class also that is used to display result in listview(I mean this is used for custom listview).
Here I'm going to add all codes what i have used in this application.
Assumes i have xml like this:-
<?xml version="1.0" encoding="UTF-8"?>
<ProductItemsResponse LIST_FOUND="true">
        <ProductItem product_category_ID='1' product_item_ID='112899'
        Chunk_Cnt='1' item_name='Jaako Rakhe Saiyan' album_name='Bhajan Sangam'
        general_info='Music Director(s): ASR, Year: null' duration='34' size='54086'
        my_selection_flag='0' operation_type='Add' sgmode='PULL'></ProductItem>
        <ProductItem product_category_ID='1' product_item_ID='112899'
        Chunk_Cnt='1' item_name='Jaako Rakhe Saiyan' album_name='Bhajan Sangam'
        general_info='Music Director(s): ASR, Year: null' duration='34' size='54086'
        my_selection_flag='0' operation_type='Add' sgmode='PULL'></ProductItem>
        <ProductItem product_category_ID='1' product_item_ID='112901'
        Chunk_Cnt='1' item_name='Prathana' album_name='Bhajan Sangam'
        general_info='Music Director(s): Anup Jalota, Year: null' duration='36'
        size='57062' my_selection_flag='0' operation_type='Add' sgmode='PULL'></ProductItem>
        <ProductItem product_category_ID='1' product_item_ID='112906'
        Chunk_Cnt='1' item_name='Durga Stuti' album_name='Ambe Ambe Maa'
        general_info='Music Director(s): Sunita Verma, Year: null' duration='45'
        size='72038' my_selection_flag='0' operation_type='Add' sgmode='PULL'></ProductItem>
</ProductItemsResponse>
Have a look on the first class that is activity of this application also.
package com.dilip.saxlist;



import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;



import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;



public class SAXParsingListViewActivity extends Activity {
    /** Called when the activity is first created. */
    private List<Playlist> playlistList= new ArrayList<Playlist>();



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        PlaylistParser countryParser = new PlaylistParser();
        InputStream inputStream = getResources().openRawResource(
                R.raw.playlist);
       
        // Parse the inputstream
        countryParser.parse(inputStream);



        // Get Countries
        List<Playlist> playlistList = countryParser.getList();
       
        Log.d("Country List", playlistList.toString());
        // Create a customized ArrayAdapter
        PlaylistArrayAdapter adapter = new PlaylistArrayAdapter(
                getApplicationContext(), R.layout.listitems, playlistList);
       
        // Get reference to ListView holder
        ListView lv = (ListView) this.findViewById(R.id.playlistlv);
       
        // Set the ListView adapter
        lv.setAdapter(adapter);
    }
}



Now have a look on Second class named playlistparser.java.
package com.dilip.saxlist;



import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import android.util.Log;



public class PlaylistParser {



    //private static final String tag = "CountryParser";
    //private static final String FILE_EXTENSION= ".png";
   
    private DocumentBuilderFactory factory;
    private DocumentBuilder builder;
    private final List<Playlist> list;



    public PlaylistParser() {
        this.list = new ArrayList<Playlist>();
    }



    private String getNodeValue(NamedNodeMap map, String key) {
        String nodeValue = null;
        Node node = map.getNamedItem(key);
        if (node != null) {
            nodeValue = node.getNodeValue();
        }
        return nodeValue;
    }



    public List<Playlist> getList() {
        return this.list;
    }



    /**
     * Parse XML file containing body part X/Y/Description
     *
     * @param inStream
     */
    public void parse(InputStream inStream) {
        try {
            // TODO: after we must do a cache of this XML!!!!
            this.factory = DocumentBuilderFactory.newInstance();
            this.builder = this.factory.newDocumentBuilder();
            this.builder.isValidating();
            Document doc = this.builder.parse(inStream, null);



            doc.getDocumentElement().normalize();



            NodeList playlistList = doc.getElementsByTagName("ProductItem");
            final int length = playlistList.getLength();



            for (int i = 0; i < length; i++) {
                final NamedNodeMap attr = playlistList.item(i).getAttributes();
                final String product_category_ID = getNodeValue(attr, "product_category_ID");
                final String product_item_ID = getNodeValue(attr, "product_item_ID");
                final String Chunk_Cnt = getNodeValue(attr, "Chunk_Cnt");
                final String item_name = getNodeValue(attr, "item_name");
                final String album_name = getNodeValue(attr, "album_name");
                final String general_info = getNodeValue(attr, "general_info");
                final String duration = getNodeValue(attr, "duration");
                final String size = getNodeValue(attr, "size");
                final String my_selection_flag = getNodeValue(attr, "my_selection_flag");
                final String operation_type = getNodeValue(attr, "operation_type");
                final String sgmode = getNodeValue(attr, "sgmode");
           
               
                // Construct Country object
                Playlist country = new Playlist(product_category_ID, product_item_ID,
                        Chunk_Cnt,album_name,general_info,duration,size,my_selection_flag,operation_type,sgmode,  sgmode);
               
                // Add to list
                this.list.add(country);
               
                //Log.d(tag, country.toString());
            }
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }
}
Now have a look on third class named playlist.java.
/**
 *
 */
package com.dilip.saxlist;

/**
 * @author dilip
 *
 */
public class Playlist
{
    public String product_category_ID;
    public String product_item_ID;
    public String Chunk_Cnt;
    public String item_name ;
    public String album_name ;
    public String general_info;
    public String duration ;
    public String size ;
    public String my_selection_flag;
    public String operation_type ;
    public String sgmode ;
    public String resourceId;

    public Playlist()
        {
            // TODO Auto-generated constructor stub
        }

    public Playlist(String product_category_ID, String product_item_ID,
            String Chunk_Cnt, String item_name,String album_name,String general_info,
            String duration ,String size,String my_selection_flag,String operation_type,
            String sgmode)
        {
            this.product_category_ID = product_category_ID;
            this.product_item_ID = product_item_ID;
            this.Chunk_Cnt= Chunk_Cnt;
            this.item_name=item_name;
            this.album_name=album_name;
            this.general_info=general_info;
            this.duration=duration;
            this.size=size;
            this.my_selection_flag=my_selection_flag;
            this.operation_type=operation_type;
            this.sgmode=sgmode;
            //this.resourceId = resourceFilePath;
        }

    @Override
    public String toString()
        {
            return this.product_category_ID;
        }
}
And finally have used our last class that is used for custom listview named PlaylistArrayAdapter.java. 

package com.dilip.saxlist;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PlaylistArrayAdapter extends ArrayAdapter<Playlist> {

    private static final String tag = "playlistArrayAdapter";
    //private static final String ASSETS_DIR = "images/";
    private Context context;

   
    private TextView product_category_ID;
    private TextView product_item_ID;
    private TextView Chunk_Cnt;
    private TextView item_name;
    private TextView album_name;
    private TextView general_info;
    private TextView duration;
    private TextView size;
    private TextView my_selection_flag;
    private TextView operation_type;
    private TextView sgmode;
    private List<Playlist> countries = new ArrayList<Playlist>();

    public PlaylistArrayAdapter(Context context, int textViewResourceId,
            List<Playlist> objects) {
        super(context, textViewResourceId, objects);
        this.context = context;
        this.countries = objects;
    }

    public int getCount() {
        return this.countries.size();
    }

    public Playlist getItem(int index) {
        return this.countries.get(index);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        if (row == null) {
            // ROW INFLATION
            Log.d(tag, "Starting XML Row Inflation ... ");
            LayoutInflater inflater = (LayoutInflater) this.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.listitems, parent, false);
            Log.d(tag, "Successfully completed XML Row Inflation!");
        }

        // Get item
        Playlist playlist = getItem(position);
       
        // Get reference to product_category_ID
        product_category_ID=(TextView)row.findViewById(R.id.product_category_ID);   
        // Get reference to TextView - product_item_ID
        product_item_ID = (TextView) row.findViewById(R.id.product_item_ID);
        // Get reference to TextView - Chunk_Cnt
        Chunk_Cnt = (TextView) row.findViewById(R.id.Chunk_Cnt);
        // Get reference to TextView - item_name
        item_name = (TextView) row.findViewById(R.id.item_name);
        // Get reference to TextView - album_name
        album_name = (TextView) row.findViewById(R.id.album_name);
        // Get reference to TextView - general_info
        general_info = (TextView) row.findViewById(R.id.general_info);
        // Get reference to TextView - duration
        duration = (TextView) row.findViewById(R.id.duration);
        // Get reference to TextView - size
        size = (TextView) row.findViewById(R.id.size);
        // Get reference to TextView - my_selection_flag
        my_selection_flag = (TextView) row.findViewById(R.id.my_selection_flag);
        // Get reference to TextView - operation_type
        operation_type = (TextView) row.findViewById(R.id.operation_type);
        // Get reference to TextView - sgmode
        sgmode = (TextView) row.findViewById(R.id.sgmode);
        //Set product_category_ID
        product_category_ID.setText(playlist.product_category_ID);
        //Set product_item_ID
        product_item_ID.setText(playlist.product_item_ID);
        //Set Chunk_Cnt
        Chunk_Cnt.setText(playlist.Chunk_Cnt);
        //Set item_name
        item_name.setText(playlist.item_name);
        //Set album_name
        album_name.setText(playlist.album_name);
        //Set general_info
        general_info.setText(playlist.general_info);
        //Set duration
        duration.setText(playlist.duration);
        //Set size
        size.setText(playlist.size);
        //Set my_selection_flag
        my_selection_flag.setText(playlist.my_selection_flag);
        // Set playlist operation_type
        operation_type.setText(playlist.operation_type);
        // Set playlist sgmode
        sgmode.setText(playlist.sgmode);
        return row;
    }
}

Now have a look on layout part ,I have used two layout one for listview and another for listitems.

main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="wrap_content"
  android:background="@drawable/sea"
  android:layout_height="wrap_content">
<ListView
      android:id="@+id/playlistlv"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
  </ListView>
</LinearLayout>

listitems.xml
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
        android:text="product_category_ID-"
        android:layout_width="wrap_content"
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_height="wrap_content" />
        <TextView
        android:id="@+id/product_category_ID"
        android:text="product_category_ID"
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="fill_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <TextView
        android:text="product_item_ID-"
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <TextView
        android:id="@+id/product_item_ID"
        android:textColor="#000000"
        android:text="product_item_ID "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
        android:text="Chunk_Cnt-"
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <TextView
        android:id="@+id/Chunk_Cnt"
        android:text="Chunk_Cnt "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
       
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
        android:text="item_name "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <TextView
        android:id="@+id/item_name"
        android:text="item_name "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
        android:text="album_name "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
        <TextView
        android:id="@+id/album_name"
        android:text="album_name "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
       
    </LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:text="general_info "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/general_info"
        android:text="general_info "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:text="duration "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/duration"
        android:text="duration "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
   <TextView
        android:text="size "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
   <TextView
        android:id="@+id/size"
        android:text="size "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:text="my_selection_flag "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/my_selection_flag"
        android:text="my_selection_flag "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
   
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:text="operation_type "
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/operation_type"
        android:text="operation_type "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView
        android:text="sgmode "
        android:textStyle="bold"
        android:textColor="#ff0000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/sgmode"
        android:text="sgmode "
        android:textColor="#000000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

</LinearLayout>

manifest.xml.
 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.dilip.saxlist"
    android:versionCode="1"
    android:versionName="1.0" >



    <uses-sdk android:minSdkVersion="8" />



    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".SAXParsingListViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>



</manifest>
In this application, we have placed xml file in resource->row folder.
Finally our output is this:-








Comments

Post a Comment

Popular posts from this blog

Android O New Features Overview

This post assumes, you are an experienced developer who wants to get started with the latest version of Android. Android O is not a huge update to the OS and application framework like M but it still has many useful features for both developer and an user. Android O has focus on below areas. Notification redesigned Picture-in-Picture(PIP)  Visual adaption for different devices  Battery life improved Setting app reorganized Notification redesigned: Android O notification changes includes more easy and manageable way to manager your notification behavior and settings. It includes: Notification Channel: Notification channel allows you to create user customizable channel for each type of notification you wanna display. A single application can have multiple channel, a separate channel for each type of notification you wanna display. Having said this, you can create s separate channel for audio & image notification. User can disable specific notification channel instead

Java 8 Overview

Java 1.8 has introduced major features for the Java developers. It includes various upgrade to the Java programming, JVM, Tools and libraries. The main purpose of Java 1.8 release has been to simplify programming, utilize functional programming benefits and enable parallel programming/processing in Java programming language. Java 1.8 feature  Lambda(->) Expression Functional interfaces Default Methods in interface static method inside interface     Pre defined functional interfaces Predicate Function Consumer ::(Method reference and constructor reference by using double colon(::)operator) Stream API Date & Time API

Overview of how to develop native code with Android NDK:

  Create a jni directory and place native source code under $PROJECT/jni/... Create Android.mk directory and place it under $PROJECT/jni/... to describe source code to the NDK build system. Create Application.mk and place it under $PROJECT/jni/...to describe project in more details to the NDK build system.It is an optional. Finally need to build native source code by running '$NDK/ndk-build' from project directory or it's sub-directory. Android.mk An Android.mk file is a small build script that we write to describe sources to the NDK build system. It's syntax is like this... LOCAL_PATH:=$(call my-dir) include $(CLEAR_VARS) LOCAL_MODULE:=hello-jni LOCAL_SRC_FILES:=hello-jni.c include $(BUILD_SHARED_LIBRARY) NDK groups your sources into "modules", where each module can be one of the following: Static library Shared library We can write several module in a single 'Android.mk' or can write seve