0

how can i retrieve all the value from xml from internet using android. I have found one good tutorial and implemented it http://www.anddev.org/novice-tutorials-f8/parsing-xml-from-the-net-using-the-saxparser-t353.html, but i only able to retrieve the last item of my xml :( I want to show the result in simple ListView

This is my xml file that i host in internet http://www.rahmanrahim.com/webservicekos/allkos (sorry i can't post it properly )

this is my MainActivity.java

package com.example.cobaxmlparser;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

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

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

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {



/** Called when the activity is first created. */
@SuppressLint("NewApi")
@Override

public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.activity_main);
    /* Create a new TextView to display the parsingresult later. */
    TextView tv = new TextView(this);
    ListView view = (ListView) findViewById(R.id.view);
    String[] hasilXml = new String[21];
    int x = 0;
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    try {
        /* Create a URL we want to load some xml-data from. */
        URL url = new URL("http://www.rahmanrahim.com/webservicekos/allkos");
        HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
        //URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestMethod("GET");

        urlConnection.setDoOutput(true);
        urlConnection.connect();
        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();
        /* Create a new ContentHandler and apply it to the XML-Reader*/ 
        ExampleHandler myExampleHandler = new ExampleHandler();
        xr.setContentHandler(myExampleHandler);

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(url.openStream()));
        /* Parsing has finished. */

        /* Our ExampleHandler now provides the parsed data to us. */
        ParsedExampleDataSet parsedExampleDataSet = 
                                myExampleHandler.getParsedData();

        /* Set the result to be displayed in our GUI. */
        //tv.setText(parsedExampleDataSet.toString());
        //String cek = parsedExampleDataSet.toString(x);
        hasilXml[x] = parsedExampleDataSet.toString();
        x++;
        System.out.println("nilai x adalah : " + x);
        //tv.setText(cek);


    } catch (Exception e) {
        /* Display any Error to the GUI. */
        tv.setText("Error: " + e.getMessage());
        Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
    }
    /* Display the TextView. */
    //this.setContentView(tv);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hasilXml);
    view.setAdapter(adapter);
}

}

Here is my ExampleHandler.java

 package com.example.cobaxmlparser;


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


public class ExampleHandler extends DefaultHandler{

// ===========================================================
// Fields
// ===========================================================

private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_id_kos = false;
private boolean in_nama = false;
private boolean in_latitude = false;
private boolean in_longitude = false;
private boolean in_harga = false;
private boolean in_tampakdepan = false;
private boolean in_streetview = false;
private boolean in_alamat = false;




private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();

// ===========================================================
// Getter & Setter
// ===========================================================

public ParsedExampleDataSet getParsedData() {
    return this.myParsedExampleDataSet;
}

// ===========================================================
// Methods
// ===========================================================
@Override
public void startDocument() throws SAXException {
    this.myParsedExampleDataSet = new ParsedExampleDataSet();
}

@Override
public void endDocument() throws SAXException {
    // Nothing to do
}

/** Gets be called on opening tags like: 
 * <tag> 
 * Can provide attribute(s), when xml was like:
 * <tag attribute="attributeValue">*/
@Override
public void startElement(String namespaceURI, String localName,
        String qName, Attributes atts) throws SAXException {
    if(localName.equals("xml"))
    {
        this.in_outertag = true;
    }
    else if (localName.equals("item")) {
        this.in_innertag = true;

    }else if (localName.equals("id_kos")) {
        this.in_id_kos = true;
    }else if (localName.equals("nama"))
    {
        this.in_nama = true;
    }else if (localName.equals("alamat"))
    {
        this.in_alamat = true;
    }else if (localName.equals("latitude"))
    {
        this.in_latitude = true;
    }else if (localName.equals("longitude"))
    {
        this.in_longitude = true;
    }else if (localName.equals("harga"))
    {
        this.in_harga = true;
    }else if (localName.equals("tampakdepan"))
    {
        this.in_tampakdepan = true;
    }else if (localName.equals("streetview"))
    {
        this.in_streetview = true;
    }
    }



/** Gets be called on closing tags like: 
 * </tag> */
@Override
public void endElement(String namespaceURI, String localName, String qName)
        throws SAXException {
    if(localName.equals("xml"))
    {
        this.in_outertag = false;
    }
    else if (localName.equals("item")) {
        this.in_innertag = false;

    }else if (localName.equals("id_kos")) {
        this.in_id_kos = false;
    }else if (localName.equals("nama"))
    {
        this.in_nama = false;
    }else if (localName.equals("alamat"))
    {
        this.in_alamat = false;
    }else if (localName.equals("latitude"))
    {
        this.in_latitude = false;
    }else if (localName.equals("longitude"))
    {
        this.in_longitude = false;
    }else if (localName.equals("harga"))
    {
        this.in_harga = false;
    }else if (localName.equals("tampakdepan"))
    {
        this.in_tampakdepan = false;
    }else if (localName.equals("streetview"))
    {
        this.in_streetview = false;
    }

}

/** Gets be called on the following structure: 
 * <tag>characters</tag> */
@Override
public void characters(char ch[], int start, int length) {
    if(this.in_id_kos){
        myParsedExampleDataSet.setId_kos(new String(ch, start, length));
    }if(this.in_nama){
        myParsedExampleDataSet.setNama(new String(ch, start, length));
    }if(this.in_alamat){
        myParsedExampleDataSet.setAlamat(new String(ch, start, length));
    }if(this.in_latitude){
        myParsedExampleDataSet.setLatitude(new String(ch, start, length));
    }if(this.in_longitude){
        myParsedExampleDataSet.setLongitude(new String(ch, start, length));
    }if(this.in_harga){
        myParsedExampleDataSet.setHarga(new String(ch, start, length));
    }if(this.in_tampakdepan){
        myParsedExampleDataSet.setTampakdepan(new String(ch, start, length));
    }if(this.in_streetview){
        myParsedExampleDataSet.setStreetview(new String(ch, start, length));
    }
}

}

and the last the ParsedExampleDataSet.java

public class ParsedExampleDataSet 
{
private String id_kos = null;
private String nama = null;
private String alamat = null;
private String latitude = null;
private String longitude = null;
private String harga = null;
private String tampakdepan = "";
private String streetview = "";

public String getId_kos() {
return id_kos;
}
public void setId_kos(String id_kos) {
this.id_kos = id_kos;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
    this.nama = nama;
}


public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
    this.latitude = latitude;
}


public String getLongitude() {
    return longitude;
}


public void setLongitude(String longitude) {
    this.longitude = longitude;
}


public String getHarga() {
    return harga;
}


public void setHarga(String harga) {
    this.harga = harga;
}


public String getTampakdepan() {
    return tampakdepan;
}


public void setTampakdepan(String tampakdepan) {
    this.tampakdepan = tampakdepan;
}


public String getStreetview() {
    return streetview;
}


public void setStreetview(String streetview) {
    this.streetview = streetview;
}

public String toString(){


    return "id_kos "+this.id_kos+" nama "+this.nama+" alamat "+this.alamat+" latitude "+this.latitude+" longitude "+this.longitude+" harga "+this.harga+" tampak depan "+this.tampakdepan+" street view "+this.streetview;
}

}

from the code above i only able to get the last item Any help would really great. I am new to android and sorry for my bad english. Thanks

2 Answers 2

1

Try this..

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

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.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    String url = "http://www.rahmanrahim.com/webservicekos/allkos";
    ProgressDialog pDialog;

    ArrayList<String> hasilXml = new ArrayList<String>();

    ListView view;

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        view = (ListView) findViewById(R.id.view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
            new XmlParsing(url).executeOnExecutor(
                    AsyncTask.THREAD_POOL_EXECUTOR, new String[] { null });
        else
            new XmlParsing(url).execute(new String[] { null });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public class XmlParsing extends AsyncTask<String, Void, String> {

        // variables passed in:
        String urls;

        // constructor
        public XmlParsing(String urls) {
            this.urls = urls;
        }

        @Override
        protected void onPreExecute() {
            pDialog = ProgressDialog.show(NetActivity.this,
                    "Fetching Details..", "Please wait...", true);
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            URL url;
            try {

                url = new URL(urls);
                DocumentBuilderFactory dbf = DocumentBuilderFactory
                        .newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(new InputSource(url.openStream()));

                doc.getDocumentElement().normalize();

                NodeList nodeList = doc.getElementsByTagName("item");

                for (int i = 0; i < nodeList.getLength(); i++) {

                    Node node = nodeList.item(i);

                    Element fstElmnt = (Element) node;
                    NodeList nameList = fstElmnt.getElementsByTagName("id_kos");
                    Element nameElement = (Element) nameList.item(0);
                    nameList = nameElement.getChildNodes();

                    System.out.println("id_kos : "
                            + ((Node) nameList.item(0)).getNodeValue());

                    Element fstElmnt1 = (Element) node;
                    NodeList nameList1 = fstElmnt1.getElementsByTagName("nama");
                    Element nameElement1 = (Element) nameList1.item(0);
                    nameList1 = nameElement1.getChildNodes();

                    System.out.println("nama : "
                            + ((Node) nameList1.item(0)).getNodeValue());

                    Element fstElmnt2 = (Element) node;
                    NodeList nameList2 = fstElmnt2
                            .getElementsByTagName("alamat");
                    Element nameElement2 = (Element) nameList2.item(0);
                    nameList2 = nameElement2.getChildNodes();

                    System.out.println("alamat : "
                            + ((Node) nameList2.item(0)).getNodeValue());

                    Element fstElmnt3 = (Element) node;
                    NodeList nameList3 = fstElmnt3
                            .getElementsByTagName("latitude");
                    Element nameElement3 = (Element) nameList3.item(0);
                    nameList3 = nameElement3.getChildNodes();

                    System.out.println("latitude : "
                            + ((Node) nameList3.item(0)).getNodeValue());

                    Element fstElmnt4 = (Element) node;
                    NodeList nameList4 = fstElmnt4
                            .getElementsByTagName("longitude");
                    Element nameElement4 = (Element) nameList4.item(0);
                    nameList4 = nameElement4.getChildNodes();

                    System.out.println("longitude : "
                            + ((Node) nameList4.item(0)).getNodeValue());

                    Element fstElmnt5 = (Element) node;
                    NodeList nameList5 = fstElmnt5
                            .getElementsByTagName("harga");
                    Element nameElement5 = (Element) nameList5.item(0);
                    nameList5 = nameElement5.getChildNodes();

                    System.out.println("harga : "
                            + ((Node) nameList5.item(0)).getNodeValue());

                    Element fstElmnt6 = (Element) node;
                    NodeList nameList6 = fstElmnt6
                            .getElementsByTagName("tampakdepan");
                    Element nameElement6 = (Element) nameList6.item(0);
                    nameList6 = nameElement6.getChildNodes();

                    System.out.println("tampakdepan : "
                            + ((Node) nameList6.item(0)).getNodeValue());

                    hasilXml.add("id_kos : "
                            + ((Node) nameList.item(0)).getNodeValue()
                            + "nama : "
                            + ((Node) nameList1.item(0)).getNodeValue()
                            + "alamat : "
                            + ((Node) nameList2.item(0)).getNodeValue()
                            + "latitude : "
                            + ((Node) nameList3.item(0)).getNodeValue()
                            + "longitude : "
                            + ((Node) nameList4.item(0)).getNodeValue()
                            + "harga : "
                            + ((Node) nameList5.item(0)).getNodeValue()
                            + "tampakdepan : "
                            + ((Node) nameList6.item(0)).getNodeValue());
                }

            } catch (MalformedURLException 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();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Now we have your JSONObject, play around with it.
            if (pDialog.isShowing())
                pDialog.dismiss();
             ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, hasilXml);
                view.setAdapter(adapter);
        }

    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

[Tamilan] Thank you so much for your answer, i have tried it but i get error and my app force close, in the logcat there java.lang.NullPointerException,at com.example.cobaxmlparser.MainActivity$XmlParsing.onPostExecute(MainActivity.java:193)
@user2997327 which line is 193
it is solved already.. Big thanks to you @Tamilan. i only change the netactivity with mainactivity :p. once again, big thanks to you :D
i already accept but can't upvote. my reputation is not high enough to upvote.. Thank you
0

You are running network related operation on the ui thread.

Move

HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();

to a thread or AsyncTask

To parse xml use XmlPullParser. There is example in the below link.

http://developer.android.com/training/basics/network-ops/xml.html

1 Comment

i still confused, do i need to change all the code ? how to use the AsyncTask ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.