Android XML解析listview

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android XML解析listview相关的知识,希望对你有一定的参考价值。

我使用本教程http://www.androidbegin.com/tutorial/android-xml-parse-images-and-texts-tutorial/来实现XML解析,如果我想将url更改为这个http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml,该怎么做?因为xml格式不同。如果有类似的问题请通知我。谢谢。

每个listitem都有一个标签,但我的网址只包含所有标签的'Infos'。

main activity.Java

   package eason.xml;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends Activity {
    // Declare Variables
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;

    static String ID = "Id";
    static String NAME = "Name";
    static String WEBSITE = "Website";
    static String PICTURE1 = "Picture";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the view from listview_main.xml
        setContentView(R.layout.listview_main);
        // Execute DownloadJSON AsyncTask
        new DownloadXML().execute();
    }

    // DownloadJSON AsyncTask
    private class DownloadXML extends AsyncTask<Void, Void, Void> {
        private void parseRequestResultXML(InputStream stream) {

            arraylist=new ArrayList<HashMap<String,String>>();

            try {
                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = factory.newPullParser();
                parser.setInput(stream, null);

                HashMap<String, String> map = null;

                int eventType = parser.getEventType();
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    switch (parser.getEventType()) {

                        case XmlPullParser.START_DOCUMENT:
                            //Log.i("TAG", " Start document " + parser.getName());
                            break;

                        case XmlPullParser.START_TAG:
                            //Log.i("TAG", " Start tag " + parser.getName());
                            String tag=parser.getName();

                            if(tag.equals("Info")){ //read values from Info tag
                                Log.i("TAG","reading info");
                                ID=parser.getAttributeValue(null, "Id");
                                NAME=parser.getAttributeValue(null, "Name");
                                WEBSITE=parser.getAttributeValue(null, "Website");
                                PICTURE1=parser.getAttributeValue(null,"Picture1");
                                //do same for other values

                                map = new HashMap<String, String>();
                                map.put("Id", ID);
                                map.put("Name", NAME);
                                map.put("Website", WEBSITE);
                                arraylist.add(map);
                            }

                            break;

                        case XmlPullParser.END_TAG:
                            //Log.i("TAG", " End tag " + parser.getName());
                            break;

                        default:
                            break;
                    }
                    eventType=parser.next(); //get next event type
                }

                //reading all values from list
                for (Map<String,String> e : arraylist) {
                    Log.d("TAG"," Row ID "+e.get("Id")+" Name "+e.get("Name")+" Website "+e.get("Website")+" Picture1 "+e.get("Picture1"));
                }

            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(MainActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android XML Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
            InputStream stream = parser.getInputStreamFromUrl("http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml");
            if (stream != null) {
                try {parseRequestResultXML(stream);
                stream.close();}catch(IOException e1) {
                    e1.printStackTrace();
                }
            }return null;
        }
        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            // Binds the Adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }

}}

ListView适配器

package eason.xml;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables
    Context context;
    LayoutInflater inflater;
    ArrayList<HashMap<String, String>> data;
    ImageLoader imageLoader;
    HashMap<String, String> resultp = new HashMap<String, String>();

    public ListViewAdapter(Context context,
                           ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        data = arraylist;
        imageLoader = new ImageLoader(context);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // Declare Variables
        TextView NAME;
        TextView START;
        TextView WEBSITE;
        ImageView Picture1;

        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.listview_item, parent, false);
        // Get the position
        resultp = data.get(position);

        // Locate the TextViews in listview_item.xml
        NAME = (TextView) itemView.findViewById(R.id.rank);
        START = (TextView) itemView.findViewById(R.id.country);
        WEBSITE = (TextView) itemView.findViewById(R.id.population);

        // Locate the ImageView in listview_item.xml
        Picture1 = (ImageView) itemView.findViewById(R.id.flag);

        // Capture position and set results to the TextViews
        NAME.setText(resultp.get(MainActivity.ID));
        START.setText(resultp.get(MainActivity.NAME));
        WEBSITE.setText(resultp.get(MainActivity.WEBSITE));
        // Capture position and set results to the ImageView
        // Passes flag images URL into ImageLoader.class
        imageLoader.DisplayImage(resultp.get(MainActivity.PICTURE1), Picture1);
        // Capture ListView item click
        itemView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Get the position
                resultp = data.get(position);
                Intent intent = new Intent(context, SingleItemView.class);
                // Pass all data rank
                intent.putExtra("Id", resultp.get(MainActivity.ID));
                // Pass all data country
                intent.putExtra("Name", resultp.get(MainActivity.NAME));
                // Pass all data population
                intent.putExtra("Website",
                        resultp.get(MainActivity.WEBSITE));
                // Pass all data flag
                intent.putExtra("Picture1", resultp.get(MainActivity.PICTURE1));
                // Start SingleItemView Class
                context.startActivity(intent);

            }
        });
        return itemView;
    }
}

XML解析器

package eason.xml;

import android.util.Log;

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.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class XMLParser {

    public XMLParser() {

    }

    // Retrive XML from URL
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            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;
    }

    // Retrive DOM 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 doc;
    }

    // Retrive Node 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 "";
    }

    // Retrive Node Value
    public InputStream getInputStreamFromUrl(String url) {
        String xml = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            return httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
答案

更改getXmlFromUrl()中的URL,然后更改parser.getValue(e, **RANK**)中的键。无论您的格式是什么,您都需要指定获取数据的密钥,然后相应地保存。

另一答案

在该教程中,作者正在从XML的TEXT标记中读取值。但在您的情况下,您需要从属性名称获取值。

private void parseRequestResultXML(InputStream stream) {

        arraylist=new ArrayList<HashMap<String,String>>();

        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(stream, null);

            HashMap<String, String> map = null;

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (parser.getEventType()) {

                case XmlPullParser.START_DOCUMENT:
                    //Log.i("TAG", " Start document " + parser.getName());
                    break;

                case XmlPullParser.START_TAG:
                    //Log.i("TAG", " Start tag " + parser.getName());
                    String tag=parser.getName();

                    if(tag.equals("Info")){ //read values from Info tag
                        Log.i("TAG","reading info");
                        String id=parser.getAttributeValue(null, "Id");
                        String name=parser.getAttributeValue(null, "Name");
                        String website=parser.getAttributeValue(null, "Website");
                        //do same for other values

                        map = new HashMap<String, String>();
                        map.put("id", id);
                        map.put("name", name);
                        map.put("website", website);
                        arraylist.add(map);
                    }   

                    break;

                case XmlPullParser.END_TAG:
                    //Log.i("TAG", " End tag " + parser.getName());
                    break;

                default:
                    break;
                }
                eventType=parser.next(); //get next event type
            }

            //reading all values from list
            for (Map<String,String> e : arraylist) {
                Log.d("TAG"," Row ID "+e.get("id")+" Name "+e.get("name")+" Website "+e.get("website"));
            }

        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } 

    }

更新:在XMLParser.java中添加此方法

public InputStream getInputStreamFromUrl(String url) {
        String xml = null;
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            return httpEntity.getContent();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

doInBackground

arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
InputStream stream = parser.getInputStreamFromUrl("http://www.androidbegin.com/tutorial/xmlparseimgtxt.xml");
if (stream != null){
    parseRequestResultXML(stream);
    stream.close();
}

以上是关于Android XML解析listview的主要内容,如果未能解决你的问题,请参考以下文章

Android XML解析listview

在片段android中创建listview

不要在片段中显示列表视图项

片段中ListView的android自定义适配器

片段中 ListView 的 setOnItemClickListener

片段中ListView的setOnItemClickListener