Friday, February 10, 2017

android - XmlPullParser example

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/coordinator_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#dbe5e9"
    >
    <Button
        android:id="@+id/btn_do"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parse XML Data"
        android:layout_margin="25dp"
        android:layout_gravity="top|center_horizontal"
        />
    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/btn_do"
        app:layout_anchorGravity="bottom"
        android:layout_gravity="bottom"
        android:background="#bac7a2"
        >
    </ListView>
</android.support.design.widget.CoordinatorLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.List;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private CoordinatorLayout mCLayout;
    private Button mButtonDo;
    private ListView mListView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from XML layout
        mCLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
        mButtonDo = (Button) findViewById(R.id.btn_do);
        mListView = (ListView) findViewById(R.id.lv);

        // Set a click listener for button widget
        mButtonDo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Initialize a new StudentsPullParser instance
                StudentsPullParser pullParser = new StudentsPullParser();

                // Get the student list from xml data
                List<Student> students = pullParser.parseXMLData(mContext);

                // Initialize a new array adapter for list view
                ArrayAdapter adapter = new ArrayAdapter<>(
                        mActivity,
                        android.R.layout.simple_list_item_1,
                        students
                );

                // Specify the adapter for list view
                mListView.setAdapter(adapter);
            }
        });
   }
}
res/raw/students.xml

<?xml version="1.0" encoding="utf-8"?>
<students>
    <student>
        <roll>1</roll>
        <name>Richard Levi</name>
        <age>16</age>
    </student>
    <student>
        <roll>2</roll>
        <name>Joana Daniela</name>
        <age>14</age>
    </student>
    <student>
        <roll>3</roll>
        <name>Paula Johanna</name>
        <age>15</age>
    </student>
    <student>
        <roll>4</roll>
        <name>Therese Boje</name>
        <age>16</age>
    </student>
    <student>
        <roll>5</roll>
        <name>AistÄ— Marija</name>
        <age>15</age>
    </student>
</students>
Student.java

package com.cfsuman.me.androidcodesnippets;


public class Student {
    private int roll;
    private String name;
    private int age;

    public int getRoll() {
        return roll;
    }

    public void setRoll(int roll) {
        this.roll = roll;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "student{" +
                "roll=" + roll +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentsPullParser.java

package com.cfsuman.me.androidcodesnippets;


import android.content.Context;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

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


public class StudentsPullParser {
    private static final String STUDENT = "student";
    private static final String STUDENT_ROLL = "roll";
    private static final String STUDENT_NAME = "name";
    private static final String STUDENT_AGE = "age";

    private Student currentStudent = null;
    private String currentTag = null;

    // Initialize a new array list of student
    List<Student> students = new ArrayList<Student>();

    public List<Student> parseXMLData(Context context){
        try{
            // Initialize a new XmlPullParserFactory instance
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            /*
                XmlPullParser
                    XML Pull Parser is an interface that defines parsing functionality
                    provided in XMLPULL V1 API.

                    The current event state of the parser can be determined by calling the
                    getEventType() method. Initially, the parser is in the START_DOCUMENT state.

                    The method next() advances the parser to the next event. The int value returned
                    from next determines the current parser state and is identical to the value
                    returned from following calls to getEventType ().
            */
            XmlPullParser parser = factory.newPullParser();

            // Get the input stream from XML file's data
            InputStream stream = context.getResources().openRawResource(R.raw.students);

            // Specify the input stream for the xml pull parser
            parser.setInput(stream,null);

            // Get the vent type from XMLPullParser
            int eventType = parser.getEventType();

            // Loop through the xml data
            while(eventType!=XmlPullParser.END_DOCUMENT){ // Loop until reach the document end
                if(eventType == XmlPullParser.START_TAG){
                    /*
                        getName
                        String getName ()

                            For START_TAG or END_TAG events, the (local) name of the current element
                            is returned when namespaces are enabled. When namespace processing is
                            disabled, the raw name is returned. For ENTITY_REF events, the entity
                            name is returned. If the current event is not START_TAG, END_TAG,
                            or ENTITY_REF, null is returned.
                    */
                    if(parser.getName().equals(STUDENT)){
                        currentStudent = new Student();
                        students.add(currentStudent);
                    }else {
                        currentTag = parser.getName();
                        //Toast.makeText(context,parser.getName(),Toast.LENGTH_SHORT).show();
                    }
                }else if(eventType == XmlPullParser.END_TAG){
                    currentTag = null;
                }else if(eventType == XmlPullParser.TEXT){
                    if(currentTag!=null){
                        //Toast.makeText(context,currentTag + " || "+ parser.getText(),Toast.LENGTH_SHORT).show();
                        if(currentTag.equals(STUDENT_ROLL)){
                            /*
                                getText
                                String getText ()

                                    Returns the text content of the current event as String. The
                                    value returned depends on current event type, for example for
                                    TEXT event it is element content (this is typical case when
                                    next() is used). See description of nextToken() for detailed
                                    description of possible returned values for different types of events.
                            */
                            currentStudent.setRoll(Integer.parseInt(parser.getText()));
                        }else if(currentTag.equals(STUDENT_NAME)){
                            currentStudent.setName(parser.getText());
                        }else if(currentTag.equals(STUDENT_AGE)){
                            currentStudent.setAge(Integer.parseInt(parser.getText()));
                        }
                    }
                }
                eventType = parser.next();
            }
        }catch(XmlPullParserException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

        // Return the student list
        return students;
    }
}