Monday 18 March 2013

XML Parsing in Android

XML Parsing is quite easy in Andriod with the help of Parser Class

public class AndroidXMLParsingActivity extends Activity{




    // All static variables
    static final String URL = "http://api.androidhive.info/pizza/?format=xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";

    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String,String>>();

    private ListAdapter adapter;
    private XMLParser parser;
    private String xml;
    private Document doc;
    ProgressBar pb;
   
   
   
   



    //background running code here

    public class backgroundLoadListView extends    AsyncTask<Void, Void, Void> {

        @Override
        protected void onPostExecute(Void result) {
       
            pb.setVisibility(View.GONE);
                       
            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value

                map.put(KEY_ID, "ID id:" +parser.getValue( e, KEY_ID));
                map.put(KEY_NAME, "Name" + parser.getValue( e, KEY_NAME));
                map.put(KEY_COST, "Rs." + parser.getValue( e, KEY_COST));
                map.put(KEY_DESC, "Desc:  "+ parser.getValue( e, KEY_DESC));



                // adding HashList to ArrayList
                menuItems.add(map);

            }
            getXML();

        }
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
           
           
            pb.setVisibility(View.VISIBLE);
           
           
//             builder = new AlertDialog.Builder(this);
//            builder.setMessage("Dowmloading?").setPositiveButton("Yes", dialogClickListener)
//                .setNegativeButton("No", dialogClickListener).show();

        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            parser = new XMLParser();
            xml = parser.getXmlFromUrl(URL);
            doc = parser.getDomElement(xml);
            return null;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb= (ProgressBar)findViewById(R.id.progressBar1);


        backgroundLoadListView obj = new backgroundLoadListView();
        obj.execute();



    }


    public void getXML(){
        //    setListAdapter(adapter);
        adapter = new SimpleAdapter(this, menuItems,
                R.layout.liststyle,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                R.id.name, R.id.description, R.id.cost });



        // selecting single ListView item
        ListView lv = (ListView)findViewById(R.id.listView1);
        lv.setAdapter(adapter);
        // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.description)).getText().toString();

                Toast.makeText(getApplicationContext(), ""+name, Toast.LENGTH_SHORT).show();

            }
        });
    }
}


Parsing Class :- XMLParser.java

public class XMLParser {

    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return xml;
    }

    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));
            doc = db.parse(is);

        } catch (ParserConfigurationException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (SAXException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        } catch (IOException e) {
            Log.e("Error: ", e.getMessage());
            return null;
        }

        return doc;
    }

    public String getValue(Element item, String str) {
        NodeList n = item.getElementsByTagName(str);
        return this.getElementValue(n.item(0));
    }

    public final String getElementValue( Node elem ) {
        Node child;
        if( elem != null){
            if (elem.hasChildNodes()){
                for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                    if( child.getNodeType() == Node.TEXT_NODE  ){
                        return child.getNodeValue();
                    }
                }
            }
        }
        return "";
    }

}










Resource File :- liststyle.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:padding="5dp"
    android:background="#00ffee" >
        
    <ImageView
        android:id="@+id/productimage"
        android:layout_width="75dp"
        android:layout_height="75dp"
        android:background="#11ddcc"
   />
    <LinearLayout
        android:id="@+id/layoutvertical"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:background="#0011FF"
        android:paddingLeft="5dp"
        android:layout_marginLeft="5dp"
        >      
    <TextView
        android:id="@+id/name"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
       
        />
    <TextView
        android:id="@+id/description"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
       
        />
    <TextView
        android:id="@+id/cost"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:textColor="#ffffff"
        />     
       
    </LinearLayout>
   
   

</LinearLayout>


activity_mail.xml
<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" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
>
    </ListView>

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="184dp"
        android:layout_marginLeft="125dp"
       
         />
       

</RelativeLayout>
Don't Forget to add Permission for internet in the Manifest File
XML Source

Here is the output

1 comment:

  1. There is a very simple link that i have found about using xml parsing in android i have used it and it also gives demo files to download contains good explanation of code an awesome link that made my day

    http://geeksprogrammings.blogspot.in/2014/07/xml-parsing-in-android.html

    ReplyDelete