Click here to Skip to main content
12,079,091 members (47,518 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: Mobile Android
i am trying to fetch xml data in listview,following is the i am using
//code for parsing xml data//

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
 
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{
public String getXmlFromUrl(String url) {
    String xml = null;
 
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://itemsongs/assets/xml/itemsong_main.xml");
 
        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;
	}
//GETTING DOCUMENT OBJECT MODEL ELEMENT
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 DOM
        return doc;
	}
 
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}
//GETTING NODES 
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 "";
  } 
 

//All static variables
	static final String URL = "http://itemsongs/assets/xml/itemsong_main.xml";
//XML node keys
	static final String KEY_ITEM = "movie"; // parent node

 
	XMLParser parser = new XMLParser();
	String xml = parser.getXmlFromUrl("http://itemsongs/assets/xml/itemsong_main.xml"); // getting XML
	Document doc = parser.getDomElement(xml); // getting DOM element

	NodeList nl = doc.getElementsByTagName("movie");{
 
//looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			String name = parser.getValue(e, "KEY_NAME"); // name child value
			String cost = parser.getValue(e, "KEY_COST"); // cost child value
			String description = parser.getValue(e, "KEY_DESC"); // description child value
		}
	}
}
// i am getting error "e cannot be resolved to a variable" can anybody please suggest what should i do.
i am using XMLParser code with the following code as MainActivity,though i am not getting any error but the code is not working..........please help ,i am completely lost...
//code for MainActivity.java//

 
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.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
 
public class MainActivity extends ListActivity {
	 
    // All static variables
    static final String URL = "http://ishirsoft.com/itemsongs/assets/xml/itemsong_main.xml";
    // XML node keys
    static final String KEY_ITEM = "movie"; // parent node
    
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        ArrayList<hashmap><string,>> menuItems = new ArrayList<hashmap><string,>>();
 
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl("http://ishirsoft.com/itemsongs/assets/xml/itemsong_main.xml"); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element
 
        NodeList nl = doc.getElementsByTagName("movie");
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<string,> map = new HashMap<string,>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put("name", parser.getValue(e, "name"));
           // map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
           // map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
           // map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
 
            // adding HashList to ArrayList
            menuItems.add(map);
        }
 
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.activity_main,
                new String[] { KEY_ITEM }, new int[] {
                       R.id.listView1 });
 
        setListAdapter(adapter);
 
        // selecting single ListView item
        ListView lv = getListView();
                // listening to single listitem click
        lv.setOnItemClickListener(new OnItemClickListener() {
 
            
            public void onItemClick(AdapterView                    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.desciption)).getText().toString();
 
                // Starting new intent
            	Intent i= new Intent(MainActivity.this,XMLParser.class);
               // i.putExtra(KEY_ITEM, "movie");
                //in.putExtra(KEY_COST, cost);
               // in.putExtra(KEY_DESC, description);
                startActivity(i);
 
            }
        });
    }
}
Posted 10-Jul-12 5:49am
Edited 11-Jul-12 1:48am
v2
Comments
azhar eqbal 13-Jul-12 2:57am
   
guys!please do something man,i can't tell you people how much important this is

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Hi dude try this code for getting String array from xml file into listView

RelativeLayout rl=(RelativeLayout) findViewById(R.id.rl);
ListView list=new ListView(this);
        
ArrayAdapter<charsequence> adp=ArrayAdapter.createFromResource(this,
                R.array.str, android.R.layout.simple_list_item_1);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(adp);
rl.addView(list); </charsequence>

My xml file :

<string-array name="str">
	    <item>List 1</item>
	    <item>List 2</item>
	    <item>List 3</item>
	    <item>List 4</item>
	</string-array>

Further More Details Click Here
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web01 | 2.8.160212.1 | Last Updated 31 Jul 2012
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100