Sunday, February 5, 2017

android - XmlResourceParser 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="#f2f1e9"
    >
    <Button
        android:id="@+id/btn"
        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"
        />
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_anchor="@id/btn"
        android:layout_gravity="bottom|center_horizontal"
        app:layout_anchorGravity="bottom|center_horizontal"
        android:textSize="20sp"
        android:gravity="center_horizontal"
        />
</android.support.design.widget.CoordinatorLayout>
res/xml/students.xml

<?xml version="1.0" encoding="utf-8"?>
<students>
    <student
        firstname="Jenny"
        lastname="Jones"
        age="25"
        />
    <student
        firstname="Felicia"
        lastname="Ioana"
        age="26"
        />
    <student
        firstname="Emma"
        lastname="Louise"
        age="24"
        />
    <student
        firstname="Amanda"
        lastname="Sophia"
        age="23"
        />
</students>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;


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

    private CoordinatorLayout mCLayout;
    private Button mButton;
    private TextView mTextView;


    @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);
        mButton = (Button) findViewById(R.id.btn);
        mTextView = (TextView) findViewById(R.id.tv);

        // Initialize a new click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Empty the TextView
                mTextView.setText("");

                /*
                    XmlResourceParser
                        The XML parsing interface returned for an XML resource. This is a standard
                        XmlPullParser interface, as well as an extended AttributeSet interface and
                        an additional close() method on this interface for the client to indicate
                        when it is done reading the resource.
                */
                // Initialize a XmlResourceParser instance
                XmlResourceParser parser = getResources().getXml(R.xml.students);

                // Process the XML data
                try{
                    processXMLData(parser);
                }catch(IOException e){
                    e.printStackTrace();
                }catch (XmlPullParserException e){
                    // This exception is thrown to signal XML Pull Parser related faults.
                    e.printStackTrace();
                }
            }
        });
    }

    // Custom method to process XML data
    protected void processXMLData(XmlResourceParser parser)throws IOException,XmlPullParserException{
        int eventType = -1;

        // Loop through the XML data
        while(eventType!=parser.END_DOCUMENT){
            if(eventType == XmlResourceParser.START_TAG){
               String studentValue = parser.getName();
                if (studentValue.equals("student")){
                    String firstName = parser.getAttributeValue(null,"firstname");
                    String lastName = parser.getAttributeValue(null,"lastname");
                    String age = parser.getAttributeValue(null,"age");
                    String fullName = firstName + " " + lastName;
                    displayValues(fullName,age);
                }
            }
            /*
                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 ().

                The following event types are seen by next()

                    START_TAG
                        An XML start tag was read.
                    TEXT
                        Text content was read; the text content can be retrieved using the getText()
                        method. (when in validating mode next() will not report ignorable
                        whitespace, use nextToken() instead)
                    END_TAG
                        An end tag was read
                    END_DOCUMENT
                        No more events are available
            */
            eventType = parser.next();
        }
    }

    // Custom method to format XML data to display
    protected void displayValues(String fullName, String age){
        mTextView.setText(mTextView.getText() +"\n\n"+ fullName + " \nAge : " + age);
    }
}