Click here to Skip to main content
15,893,486 members

How to get xml data into list view

azhar eqbal asked:

Open original thread
i am trying to fetch xml data in listview,following is the i am using
Java
//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...
Java
//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);
 
            }
        });
    }
}
Tags: Mobile Apps (Android)

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900