Thursday, 10 April 2014

Android XML Parsing Tutorial


 MainActivity.java

 package com.example.simplexmlparsing;

import android.content.Context;
import android.view.Menu;

public class MainActivity extends Activity {

    public static void responces(Context conn,ArrayList<Datalist> arr){                       
    }   
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
               
       int no=1;
       WebAPIHelper webAPIHelper = new WebAPIHelper(no, con,"Please wait");
       webAPIHelper.execute("your xml url type");
    }
}

WebAPIHelper.java

package com.example.simplexmlparsing;

import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class WebAPIHelper extends AsyncTask<String, Integer, Long> {
    private ProgressDialog progressDlg;

    private Document response;
    private int requestNumber;
    private String loadingMessage;
    Context con;
    private WebAPIRequest webAPIRequest = new WebAPIRequest();

    public WebAPIHelper() {

    }

    public WebAPIHelper(int requestNumber, Context context, String msg) {
        con = context;
        progressDlg = new ProgressDialog(con);
        this.requestNumber = requestNumber;
        loadingMessage = msg;
    }

    protected void onPreExecute() {
        // if(loadingMessage!="")
        // {
        progressDlg.setMessage(loadingMessage);
        progressDlg.show();
        // }
    }

    protected Long doInBackground(String... urls) {
        response = webAPIRequest.performGet(urls[0]);
        return null;
    }

    protected void onPostExecute(Long i) {

        if (requestNumber == 1) {
           
            ArrayList<Datalist> NOtification_List = null;
           
            if (response != null) {
               
                Element node = (Element) response.getElementsByTagName("root").item(0);
                NodeList nlist = node.getElementsByTagName("result");
               
                for (int j = 0; j < nlist.getLength(); j++) {
                   
                    if (NOtification_List == null) {
                       
                        NOtification_List = new ArrayList<Datalist>();
                    }
                   
                    Datalist datalist = new Datalist();
                    Element childNode = (Element) nlist.item(j);

                    datalist.name= getValueFromNode(childNode,"Element name");
                   
                    NOtification_List.add(datalist);

                }
            }    
        }       
        progressDlg.dismiss();
    }

    String getValueFromNode(Element childNode, String tagName) {
        String strValue = "";
        try {
            Element node = (Element) childNode.getElementsByTagName(tagName)
                    .item(0);
            for (int i = 0; i < node.getChildNodes().getLength(); i++) {
                strValue = strValue.concat(node.getChildNodes().item(i)
                        .getNodeValue());
            }
        } catch (Exception exp) {
        }
        return strValue;
    }

    int parseIntValue(String strValue) {
        int value = 0;
        if (strValue != null && strValue.length() > 0) {
            value = Integer.parseInt(strValue);
        }
        return value;
    }

    double parseDoubleValue(String strValue) {
        double value = 0.0;
        if (strValue != null && strValue.length() > 0) {
            // value = Float.parseFloat(strValue);
            value = Double.parseDouble(strValue);
        }
        return value;
    }
}

Datalist.java

package com.example.simplexmlparsing;
public class Datalist {
   
    public String  name;
  
}

WebAPIRequest.java


package com.example.simplexmlparsing;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class WebAPIRequest{
    public Document performGet(String url)
    {
        Document doc = null;
        try
        {
            DefaultHttpClient client = new DefaultHttpClient();
            //URI uri = new URI(url.replaceAll(' ', '%20'));

            URI uri = new URI(url);
           
            HttpGet method = new HttpGet(uri);
            HttpResponse res = client.execute(method);
            InputStream data = res.getEntity().getContent();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (URISyntaxException e)
        {
            // TODO Auto-generated catch block
            //e.printStackTrace();
             }
             catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }               
        return doc;
    }
}

XMLParser.java

 package com.example.simplexmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

    // constructor
    public XMLParser() {

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

        try {
            // defaultHttpClient
            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
        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 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 "";
     }
        public String getValue(Element item, String str) {      
            NodeList n = item.getElementsByTagName(str);      
            return this.getElementValue(n.item(0));
        }
}




No comments:

Post a Comment