Android parse XML file from Assets or internal/external storage

Android comes with SAXParserFactory and its very easy to parse an XML document using the SAX parser. In this tutorial we will learn how to parse an XML document from android assets. In our example we have a sample order file stored in the application assets folder that is being parsed and the contents are dynamically added to the display inside a scroll view.

Anything that you store in the application assets folder is not compiled basically its a raw storage facility similar to the internal or external storage in your mobile device. All you have to is get access to the asset using the AssetManager and then open the file which returns an InputStream to read its contents. If your file resides in the internal or the external storage please click here to learn how to read the file contents using its InputStream.

Android parse XML file from assets Eclipse Project
Android parse XML file from Assets or internal external storage

Android Strings Resource - strings.xml

<resources>

    <string name="app_name">Android Parse Local XML file</string>
    <string name="menu_settings">Settings</string>
    <string name="parsed_data">Here is the parsed XML data&#8230;</string>

</resources>

Sample Order XML file - order.xml

<?xml version="1.0" encoding="utf-8" ?>
<PurchaseOrder>
  <OrderId>5</OrderId>
  <CustomerId>0275125</CustomerId>
  <Email>mysamplecode@gmail.com</Email>
  <OrderItemDetail>
    <LineNumber>1</LineNumber>
    <ProductSku>12010109Y</ProductSku>
    <Quantity>2.00</Quantity>
    <Price>7.99</Price>
   </OrderItemDetail>
  <OrderItemDetail>
    <LineNumber>2</LineNumber>
    <ProductSku>12010109B</ProductSku>
    <Quantity>900</Quantity>
    <Price>83.50</Price>
   </OrderItemDetail>
  <OrderItemDetail>
    <LineNumber>3</LineNumber>
    <ProductSku>11271581Y</ProductSku>
    <Quantity>16.00</Quantity>
    <Price>8.99</Price>
   </OrderItemDetail>
</PurchaseOrder>

Android Application main Layout - activity_main.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">

 <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
  android:layout_height="wrap_content" android:layout_alignParentLeft="true"
  android:layout_alignParentTop="true" android:layout_marginTop="14dp"
  android:text="@string/parsed_data" android:textAppearance="?android:attr/textAppearanceMedium"
  android:textStyle="bold" />

 <ScrollView android:id="@+id/scrollView1"
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:layout_alignParentLeft="true" android:layout_below="@+id/textView1"
  android:layout_marginTop="10dp">

  <LinearLayout
      android:id="@+id/linearLayout1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical" />

 </ScrollView>

</RelativeLayout>

Shopping Cart Java Object - ProductInfo.java

package com.as400samplecode;

public class ProductInfo {
 
 String seqNo = null;
 String itemNumber = "";
 String quantity = "";
 String price = "";
 
 public String getSeqNo() {
  return seqNo;
 }
 public void setSeqNo(String seqNo) {
  this.seqNo = seqNo;
 }
 public String getItemNumber() {
  return itemNumber;
 }
 public void setItemNumber(String itemNumber) {
  this.itemNumber = itemNumber;
 }
 public String getQuantity() {
  return quantity;
 }
 public void setQuantity(String quantity) {
  this.quantity = quantity;
 }
 public String getPrice() {
  return price;
 }
 public void setPrice(String price) {
  this.price = price;
 }
 

}

Custom XML handler for parsing - OrderXMLHandler.java

package com.as400samplecode;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class OrderXMLHandler extends DefaultHandler {

 boolean currentElement = false;
 String currentValue = "";

 String cartId;
 String customerId;
 String email;
 ProductInfo productInfo;
 ArrayList<ProductInfo> cartList;
 
 public String getCartId() {
  return cartId;
 }

 public String getCustomerId() {
  return customerId;
 }
 
 public String getEmail() {
  return email;
 }

 public ArrayList<ProductInfo> getCartList() {
  return cartList;
 }
 
 public void startElement(String uri, String localName, String qName,
   Attributes attributes) throws SAXException {

  currentElement = true;

  if (qName.equals("PurchaseOrder")){
   cartList = new ArrayList<ProductInfo>();
  } 
  else if (qName.equals("OrderItemDetail")) {
   productInfo = new ProductInfo();
  }

 }

 public void endElement(String uri, String localName, String qName)
 throws SAXException {

  currentElement = false;

  if (qName.equalsIgnoreCase("OrderId"))
   cartId = currentValue.trim();
  else if (qName.equalsIgnoreCase("CustomerId"))
   customerId = currentValue.trim();
  else if (qName.equalsIgnoreCase("Email"))
   email = currentValue.trim();

  else if (qName.equalsIgnoreCase("LineNumber"))
   productInfo.setSeqNo(currentValue.trim());
  else if (qName.equalsIgnoreCase("ProductSku"))
   productInfo.setItemNumber(currentValue.trim());
  else if (qName.equalsIgnoreCase("Quantity"))
   productInfo.setQuantity(currentValue.trim());
  else if (qName.equalsIgnoreCase("Price"))
   productInfo.setPrice(currentValue.trim());
  else if (qName.equalsIgnoreCase("OrderItemDetail"))
   cartList.add(productInfo);

  currentValue = "";
 }

 public void characters(char[] ch, int start, int length)
 throws SAXException {

  if (currentElement) {
   currentValue = currentValue + new String(ch, start, length);
  }

 }

}

Android Application main Activity - MainActivity.java

package com.as400samplecode;

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

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.util.Log;
import android.view.Menu;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    private void parseXML() {
        AssetManager assetManager = getBaseContext().getAssets();
        try {
            InputStream is = assetManager.open("order.xml");
            SAXParserFactory spf = SAXParserFactory.newInstance();
   SAXParser sp = spf.newSAXParser();
   XMLReader xr = sp.getXMLReader();

   OrderXMLHandler myXMLHandler = new OrderXMLHandler();
   xr.setContentHandler(myXMLHandler);
   InputSource inStream = new InputSource(is);
   xr.parse(inStream);
   
   String cartId = myXMLHandler.getCartId();
   String customerId = myXMLHandler.getCustomerId();
   String email = myXMLHandler.getEmail();
   
   Log.v("abc", cartId);
   LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1);
   TextView tv = new TextView(this);
         tv.setText("Cart Id: " + cartId);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Customer Id: " + customerId);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Email : " + email);
         ll.addView(tv);
         tv = new TextView(this);
         tv.setText("Shopping Cart Info --->");
         ll.addView(tv);
         
   ArrayList<ProductInfo> cartList = myXMLHandler.getCartList();
   for(ProductInfo productInfo: cartList){
    tv = new TextView(this);
          tv.setText("Line No : " + productInfo.getSeqNo());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Item No : " + productInfo.getItemNumber());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Quantity : " + productInfo.getQuantity());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("Price : " + productInfo.getPrice());
          ll.addView(tv);
          tv = new TextView(this);
          tv.setText("---");
          ll.addView(tv);
   }
   
            is.close();
            
        } catch (Exception e) {
            e.printStackTrace(); 
        }
       

    }


}

Recommended Reading

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.