-1

我正在尝试编写一个解析 xml 代码并在列表视图中写入每个节点的值的代码

我正在使用这个 XML

http://www.iqraa.com/rss/CustomizedServices.aspx?Service=TvGuide

我尝试遵循本教程

http://www.androidhive.info/2011/11/android-xml-parsing-tutorial

但没有任何作用

请提供任何帮助:(

这是xmlparser的代码

公共类 XMLParser {

public XMLParser() {

}

/**
 * Getting XML from URL making HTTP request
 * 
 * @param url
 *            string
 * */
public String getXmlFromUrl(String url) {
    String xml = null;

    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        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 XML DOM element
 * 
 * @param XML
 *            string
 * */
public Document getDomElement(String xml) {
    Document doc = null;

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    // dbf.setCoalescing(true);
    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 doc;
}

/**
 * Getting node value
 * 
 * @param elem
 *            element
 */
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 "";
}

/**
 * Getting node value
 * 
 * @param Element
 *            node
 * @param key
 *            string
 * */
public String getValue(Element item, String str) {
    NodeList n = item.getElementsByTagName(str);
    return this.getElementValue(n.item(0));
}

}

这是 MainActivity 的代码

公共类 MainActivity 扩展 ListActivity {

static final String URL = "http://iqraa.com/rss/CustomizedServices.aspx?Service=TvGuide";
// XML node keys
static final String KEY_PITEM = "ProgramItem"; // parent node

static final String KEY_PNAME = "ProgramName";
static final String KEY_LINK = "Link";
static final String KEY_STARTTIME = "StartTime";
static final String KEY_CHANNEL = "Channel";
static final String KEY_SCHEDULE = "ScheduleDate";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

    XMLParser parser = new XMLParser();
    String xml = parser.getXmlFromUrl(URL); // getting XML

    Log.i("Inside 1  Oncreate", "On create done");
    Document doc = parser.getDomElement(xml); // getting DOM element

    NodeList nl = doc.getElementsByTagName(KEY_PITEM);

    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();
        Element e = (Element) nl.item(i);
        // adding each child node to HashMap key => value
        map.put(KEY_PNAME, parser.getValue(e, KEY_PNAME));
        //map.put(KEY_LINK, parser.getValue(e, KEY_LINK));
        Log.i("Inside 1  Oncreate", "FOR LOOOOOOP ");
        map.put(KEY_STARTTIME,parser.getValue(e, KEY_STARTTIME));
        map.put(KEY_CHANNEL,parser.getValue(e, KEY_CHANNEL));
        map.put(KEY_SCHEDULE, parser.getValue(e, KEY_SCHEDULE));

        // adding HashList to ArrayList
        menuItems.add(map);
    }


    // Adding menuItems to ListView
    ListAdapter adapter = new SimpleAdapter(this, menuItems,
            R.layout.list_item,
            new String[] { KEY_PNAME, KEY_STARTTIME, KEY_CHANNEL}, new int[] {
                    R.id.name, R.id.stime, R.id.channel });
    Log.i("Inside 3  Oncreate", "2222222");

    setListAdapter(adapter);

    // selecting single ListView item
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            Log.i("Inside 1  Oncreate", "44444444");
            String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
            String channel = ((TextView) view.findViewById(R.id.channel)).getText().toString();
            String stime = ((TextView) view.findViewById(R.id.stime)).getText().toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
            in.putExtra(KEY_PNAME, name);
            in.putExtra(KEY_CHANNEL, channel);
            in.putExtra(KEY_STARTTIME, stime);
            startActivity(in);

        }
    });


}

}

4

1 回答 1

0
you have to add permissions for this parsing xml in manifest.

add this line in Manifest file
 <uses-permission android:name="android.permission.INTERNET"/>

See your activity class here Now it is working  fine.Run this Example in Device,for  Emulator check permissions may be there are any restrictions.

package com.rmn.xmlparser;

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.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
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;
import android.widget.TextView;

public class ListxmlActivity extends Activity {
    static final String URL = "http://iqraa.com/rss/CustomizedServices.aspx?Service=TvGuide";
    // XML node keys
    static final String KEY_PITEM = "ProgramItem"; // parent node

    static final String KEY_PNAME = "ProgramName";
    static final String KEY_LINK = "Link";
    static final String KEY_STARTTIME = "StartTime";
    static final String KEY_CHANNEL = "Channel";
    static final String KEY_SCHEDULE = "ScheduleDate";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
        // selecting single ListView item
        ListView lv =(ListView) findViewById(R.id.list);

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML from URL
        Document doc = parser.getDomElement(xml); // getting DOM element


        NodeList nl = doc.getElementsByTagName(KEY_PITEM);

        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_PNAME, parser.getValue(e, KEY_PNAME));
            map.put(KEY_STARTTIME,parser.getValue(e, KEY_STARTTIME));
            map.put(KEY_CHANNEL,parser.getValue(e, KEY_CHANNEL));
            map.put(KEY_SCHEDULE, parser.getValue(e, KEY_SCHEDULE));

            // adding HashList to ArrayList
            menuItems.add(map);
        }


        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_PNAME, KEY_STARTTIME, KEY_CHANNEL}, new int[] {
                        R.id.name, R.id.stime, R.id.channel });
        Log.i("Inside 3  Oncreate", "2222222");

        lv.setAdapter(adapter);



        lv.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                Log.i("Inside 1  Oncreate", "44444444");
                String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String channel = ((TextView) view.findViewById(R.id.channel)).getText().toString();
                String stime = ((TextView) view.findViewById(R.id.stime)).getText().toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(KEY_PNAME, name);
                in.putExtra(KEY_CHANNEL, channel);
                in.putExtra(KEY_STARTTIME, stime);
                startActivity(in);

            }
        });


    }
}
于 2012-11-05T12:06:45.717 回答