AdSense

AdSense3

Thursday 8 October 2015

Android XMLPullParser

Android recommends to use XMLPullParser to parse the xml file than SAX and DOM because it is fast.

The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XMLPullParser.

Events of XmlPullParser

The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface.
START_TAG :An XML start tag was read.
TEXT :Text content was read; the text content can be retrieved using the getText() method.
END_TAG : An end tag was read.
END_DOCUMENT :No more events are available

Example of android XMLPullParser

activity_main.xml

Drag the one listview from the pallete. Now the activity_main.xml file will look like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <ListView  
  8.         android:id="@+id/listView1"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="wrap_content" >  
  11.   
  12.     </ListView>  
  13.   
  14. </RelativeLayout>  

xml document

Create an xml file named employees.xml inside the assets directory of your project.
File: employees.xml
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <employees>  
  3.     <employee>  
  4.         <id>1</id>  
  5.         <name>Sachin</name>  
  6.         <salary>50000</salary>        
  7.     </employee>  
  8.     <employee>  
  9.         <id>2</id>  
  10.         <name>Nikhil</name>  
  11.         <salary>60000</salary>    
  12.     </employee>  
  13.       
  14. </employees>  

Employee class

Now create the Employee class that corresponds to the xml file.
File: Employee.java
  1. package com.example.xmlpullparsing;  
  2. public class Employee {  
  3.      private int id;  
  4.      private String name;  
  5.      private float salary;  
  6.         public int getId() {  
  7.         return id;  
  8.     }  
  9.     public void setId(int id) {  
  10.         this.id = id;  
  11.     }  
  12.     public String getName() {  
  13.         return name;  
  14.     }  
  15.     public void setName(String name) {  
  16.         this.name = name;  
  17.     }  
  18.     public float getSalary() {  
  19.         return salary;  
  20.     }  
  21.     public void setSalary(float salary) {  
  22.         this.salary = salary;  
  23.     }  
  24.   
  25.     @Override  
  26.     public String toString() {  
  27.         return " Id= "+id + "\n Name= " + name + "\n Salary= " + salary;  
  28.     }  
  29. }  

XMLPullParserHandler class

Now write the code to parse the xml file using XMLPullParser. Here, we are returning all the employee in list.
File: XMLPullParserHandler.java
  1. package com.example.xmlpullparsing;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import org.xmlpull.v1.XmlPullParser;  
  7. import org.xmlpull.v1.XmlPullParserException;  
  8. import org.xmlpull.v1.XmlPullParserFactory;  
  9.    
  10.   
  11. public class XmlPullParserHandler {  
  12.     private List<Employee> employees= new ArrayList<Employee>();  
  13.     private Employee employee;  
  14.     private String text;  
  15.    
  16.     public List<Employee> getEmployees() {  
  17.         return employees;  
  18.     }  
  19.    
  20.     public List<Employee> parse(InputStream is) {  
  21.            try {  
  22.             XmlPullParserFactory factory = XmlPullParserFactory.newInstance();  
  23.             factory.setNamespaceAware(true);  
  24.             XmlPullParser  parser = factory.newPullParser();  
  25.    
  26.             parser.setInput(is, null);  
  27.    
  28.             int eventType = parser.getEventType();  
  29.             while (eventType != XmlPullParser.END_DOCUMENT) {  
  30.                 String tagname = parser.getName();  
  31.                 switch (eventType) {  
  32.                 case XmlPullParser.START_TAG:  
  33.                     if (tagname.equalsIgnoreCase("employee")) {  
  34.                         // create a new instance of employee  
  35.                         employee = new Employee();  
  36.                     }  
  37.                     break;  
  38.    
  39.                 case XmlPullParser.TEXT:  
  40.                     text = parser.getText();  
  41.                     break;  
  42.    
  43.                 case XmlPullParser.END_TAG:  
  44.                     if (tagname.equalsIgnoreCase("employee")) {  
  45.                         // add employee object to list  
  46.                         employees.add(employee);  
  47.                     }else if (tagname.equalsIgnoreCase("id")) {  
  48.                         employee.setId(Integer.parseInt(text));  
  49.                     }  else if (tagname.equalsIgnoreCase("name")) {  
  50.                         employee.setName(text);  
  51.                     } else if (tagname.equalsIgnoreCase("salary")) {  
  52.                         employee.setSalary(Float.parseFloat(text));  
  53.                     }   
  54.                     break;  
  55.    
  56.                 default:  
  57.                     break;  
  58.                 }  
  59.                 eventType = parser.next();  
  60.             }  
  61.    
  62.         } catch (XmlPullParserException e) {e.printStackTrace();}   
  63.         catch (IOException e) {e.printStackTrace();}  
  64.    
  65.         return employees;  
  66.     }  
  67. }  

MainActivity class

Now, write the code to display the list data in the ListView.
File: MainActivity.java
  1. package com.example.xmlpullparsing;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.List;  
  6.   
  7. import android.os.Bundle;  
  8. import android.app.Activity;  
  9. import android.view.Menu;  
  10. import android.widget.ArrayAdapter;  
  11. import android.widget.ListView;  
  12.   
  13. public class MainActivity extends Activity {  
  14.   
  15.     @Override  
  16.     protected void onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.           
  20.        ListView listView = (ListView) findViewById(R.id.listView1);  
  21.           
  22.         List<Employee> employees = null;  
  23.         try {  
  24.             XmlPullParserHandler parser = new XmlPullParserHandler();  
  25.             InputStream is=getAssets().open("employees.xml");  
  26.             employees = parser.parse(is);  
  27.               
  28.             ArrayAdapter<Employee> adapter =new ArrayAdapter<Employee>  
  29.     (this,android.R.layout.simple_list_item_1, employees);  
  30.             listView.setAdapter(adapter);  
  31.               
  32.         } catch (IOException e) {e.printStackTrace();}  
  33.           
  34.     }  
  35.   
  36.     @Override  
  37.     public boolean onCreateOptionsMenu(Menu menu) {  
  38.         // Inflate the menu; this adds items to the action bar if it is present.  
  39.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  40.         return true;  
  41.     }  
  42.       
  43. }  

Output:

XmlPullParser Tutorial

1 comment:

  1. it is really very important topic and comparatively tough topic

    ReplyDelete