Skip to main content

Parsing an XML from Online in Android

Create a fresh project and name it ParseXMLDemo
Then in the ParseXMLDemo.java file copy this code
|
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class ParseXMLDemo extends ListActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        ArrayList<String> mylist = new ArrayList<String>();
        String xml = ParseXMLMethods.getXML();
        Document doc = ParseXMLMethods.XMLfromString(xml);
        int numResults = ParseXMLMethods.numResults(doc);

        if((numResults <= 0)){
          Toast.makeText(ParseXMLDemo.this, "There is no data in the xml file", Toast.LENGTH_LONG).show();
              finish();
        }

        NodeList children = doc.getElementsByTagName("os");
        for (int i = 0; i < children.getLength(); i++)
          {
            HashMap<string string=""> map =new HashMap<string string="">();
            Element e = (Element)children.item(i);
            map.put("id", ParseXMLMethods.getValue(e, "id"));
            map.put("name", ParseXMLMethods.getValue(e, "name"));
            map.put("site", ParseXMLMethods.getValue(e, "site"));
            mylist.add(map);
          }
        ListAdapter adapter = new SimpleAdapter(this,mylist ,R .layout.list_layout,
                          new String[] { "name", "site" },
                          new int[] { R.id.title, R.id.subtitle});

       setListAdapter(adapter);

       
        final ListView lv = getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                Toast.makeText(ParseXMLDemo.this,o.get("name"), Toast.LENGTH_LONG).show();
            }
        });
    } }
            

Now create another java file inside the src folder and name it ParseXMLMethods.java and copy this contents into it.
import java.io.IOException;
import java.io.StringReader;
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.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;

public class ParseXMLMethods {

    public final static Document XMLfromString(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) {
            System.out.println("XML parse error: " + e.getMessage());
            return null;
        }
            catch (SAXException e) {
            System.out.println("Wrong XML file structure: " +e.getMessage());
            return null;
        }
            catch (IOException e) {
            System.out.println("I/O exeption: " +e.getMessage());
            return null;
        }
        return doc;
    }
     public final static String getElementValue( Node elem ) {
         Node kid;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( kid = elem.getFirstChild(); kid != null;kid = kid.getNextSibling() ){
                     if( kid.getNodeType() == Node.TEXT_NODE  ){
                         return kid.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
     public static String getXML(){
            String line = null;
            try {
           DefaultHttpClient httpClient = new DefaultHttpClient();
           HttpPost httpPost = new HttpPost("http://new ABC.com/xml/test.xml");
           HttpResponse httpResponse = httpClient.execute(httpPost);
           HttpEntity httpEntity = httpResponse.getEntity();
           line = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
             line = "Internet Connection Error >> " + e.getMessage();
            }
            return line;
    }

    public static int numResults(Document doc)
      {
        Node results = doc.getDocumentElement();
        int res = -1;
        try
        {
          res = Integer.valueOf(results.getAttributes()
                         .getNamedItem("count").getNodeValue());
        }catch(Exception e ){
            res = -1;
        }
        return res;
    }

    public static String getValue(Element item, String str)
    {
        NodeList n = item.getElementsByTagName(str);
        return ParseXMLMethods.getElementValue(n.item(0));
    }
}
in main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"> 

    <ListView
        android:id="@id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#FF0000"
        android:drawSelectorOnTop="false"/> 
</LinearLayout> 
list_layout.xml:
< ?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="7dp"> 
<TextView
    android:id="@+id/title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:padding="2dp"
    android:textSize="20dp"
    android:textStyle="bold"/> 
    <TextView
    android:id="@+id/subtitle"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="2dp"
    android:textSize="14dp"
    android:textColor="#000000"/> 
</LinearLayout> 
Strings.xml:
<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string name="hello"> Hello World, ParseXMLDemo!</string> 
    <string name="app_name"> ParseXMLDemo New ABC.com</string> 
</resources> 

Comments

Popular posts from this blog

Spannable String in Android - URL Span ,Clickable Span, Rich-Style Formatting of Textview .....

See more Android Tutorials here....... Faster Loading images in GridViews or ListViews Spannable brings lots of possibility to TextView, includes displaying various appearance of a Text and onClick callbak. The SpannableString class allows you to easily format certain pieces which are called spans of a string, by applying CharacterStyle ie,color, font, ormake it a link . Here is an example where, explained how to use spannable string to give font size, color, linking a text via clickable span and through URL Span and to strike through the text. Lets go through the example : import android.os.Bundle; import android.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.style.ClickableSpan; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.text.style.StrikethroughSpan; import android.text.style.URLSpan; import android.view.View; import android.widget.TextView; import android.widget.Toast; ...

Use Your Own SQLite in ANDROID Application or Using 'SQLite Asset Helper' to read your own databases stored in Asset folder

See more basics on Android along with interview questions See SQLite tutorial here If you want to read your own databases in ANDROID APPLICATION, this post may help you. You may be familiar by creating SQLite in Android use  SQLiteOpenHelper . Here we are going to deal with using our own databases.  I have a database named 'mydatabase.sqlite', which consist of a set of name and age of 5 students. Suppose I want to view the database, I can use SQLite database browser which you can download from here.                                                     download browser..... Through this browser we can view the databases, can even modify delete or create a new one. 'mydatabase.sqlite' with name and age of five students is browsed and viewed as shown below Now  make a zip format of database and copy this database to asse...

Passing Images between Activities in Android

in First Activity: Intent intent=new Intent(FirstClass.this, SecondClass.class); Bundle bundle=new Bundle(); bundle.putInt("image",R.drawable.ic_launcher); intent.putExtras(bundle); startActivity(intent); in Second Acticity: Bundle bundle=this.getIntent().getExtras(); int pic=bundle.getInt("image"); v.setImageResource(pic); another method: in First Activity: Drawable drawable=imgv.getDrawable(); Bitmap bitmap= ((BitmapDrawable)drawable).getBitmap(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); byte[] b = baos.toByteArray(); Intent intent=new Intent(Passimage.this,myclass.class); intent.putExtra("picture", b); startActivity(intent); in Second Acticity: Bundle extras = getIntent().getExtras(); byte[] b = extras.getByteArray("picture"); Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.lengt...