Subscribe For Free Updates!

We'll not spam mate! We promise.

Aug 9, 2012

Read Or Parse XML File From Web Server in Android

Views:

Read Or Parse XML File From Web Server in Android
To Day I will show you How to read or Parse Xml File Hosted on Web Server or Hosting Server using Android .
In this tutorial we Will Talk about How to Parse Xml file and How to Bind With List View in Android.

In This Tutorials We will be Using .
1) HTTP Request to get XML File from Web Server or Hosting Server.
2) Read Or access XML Data .



3) Bind the XML Data To List View.


So Lets Start With Http Request .

Before This I have already uploaded a detailed Tutorial  On XML to Web server or Hosting Server With the URL
(http://p-xr.com/xml/). It is recommended to understand that tutorial first. How to Upload XML File FREE On Web Server .

My uploaded XML File Contains The Following Data .

  
   1
   Mark
   6958
  
  
   2
   Wesley
   4039
  
  
   3
   Roy
   3809
  
  
   4
   Mike
   1980
  
  
   5
   Tina
   24
  
  
   6
   Ike
   3
  
If The Above Data Looks like Text then go to this link (http://p-xr.com/xml/) and right click to view Source code where you will be able to See Actual XML data.

In the Next step We simply Make a new Method Which takes a String as Aurgument and Returns back a String Value. This method is Actually Downloads or gets the Xml data through
Http Request.Code is given below :-
public static String getXML(String URl){
String line = null;
try {

 DefaultHttpClient httpClient = new DefaultHttpClient();
//WithoutAurgument HttpPost httpPost = new HttpPost("http://p-xr.com/xml");
        HttpPost httpPost = new HttpPost("URl");
 HttpResponse httpResponse = httpClient.execute(httpPost);
 HttpEntity httpEntity = httpResponse.getEntity();
 line = EntityUtils.toString(httpEntity);
 }
catch (UnsupportedEncodingException e)
{
line = "Can't connect to server";
}
catch (MalformedURLException e)
{
line = "Can't connect to server";
}
catch (IOException e) 
{
line = "Can't connect to server";
}
return line;

}


After Getting Xml Data we have to Parse it and Since Data is in XML format we will Have parse it to a Document.
Here We pass String (Argument) having Xml Data and It returns Back a dcoument.

See Code is Below
public 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;
}


So Till now We Get Data From XML hosted on WebServer and Structured XML file data
into Document File , Now We Bind the Data in List View

For Binding Data In ListView we will have to do the Following
1) Make An Activity Class
2)Extends this Activity Class to a ListActivity
3)A custom ListView with 2 lines in each list item
4)implements a on ItemClick method of ListView

The Full code of Activity Is Following
public class Main extends ListActivity {
  /** Called when the activity is first created. */
    @Override
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listplaceholder);

//Needed for the listItems
 ArrayList> mylist 
= new ArrayList>();

    //Get the xml string from the server
        String xml = XMLfunctions.getXML();
        Document doc = XMLfunctions.XMLfromString(xml);

        int numResults = XMLfunctions.numResults(doc);

        if((numResults <= 0)){
     Toast.makeText(Main.this, 
"Geen resultaten gevonden", Toast.LENGTH_LONG).show();
        finish();
        }

NodeList nodes = doc.getElementsByTagName("result");

  //fill in the list items from the XML document
for (int i = 0; i < nodes.getLength(); i++) {
HashMap map = new HashMap(); 

      Element e = (Element)nodes.item(i);
      map.put("id", XMLfunctions.getValue(e, "id"));
      map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
      map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
      mylist.add(map);
  }  

  //Make a new listadapter
 ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
                      new String[] { "name", "Score" },
                      new int[] { R.id.item_title, R.id.item_subtitle });

        setListAdapter(adapter);

 //Get the listView ( from: ListActivity )
        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView parent, 
View view, int position, long id) {
          @SuppressWarnings("unchecked")
HashMap o = 
(HashMap) lv.getItemAtPosition(position);
        Toast.makeText(Main.this,
 "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show(); 

 }
});
    }
}



Source 1 for Android 4.0
Download Code From HERE

Source 2For Android 2.2 (Recommended)
Download Code From HERE

Plese Feel Free to Socializer This Post
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

1 comments:

  1. With havin so much written content do you ever run into any problems of plagorism or copyright
    violation? My blog has a lot of completely unique content
    I've either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you know any methods to help reduce content from being stolen? I'd definitely appreciate it.
    Feel free to visit my homepage : cloud server

    ReplyDelete

Become a Fan

visual studio learn