将简单的Listview程序转换为Listview的XML解析器

发布于 2024-12-27 16:28:55 字数 8954 浏览 1 评论 0原文

我正在将列表视图示例转换为一个程序,该程序通过读取 xml 文件进行操作,然后用其内容填充列表视图。不过我似乎遇到了障碍。我不确定如何处理我为第一个示例制作的适配器以及如何在这个新程序中使用它,任何指针将不胜感激。 这是主要的

Phonebook phonebook = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView list = (ListView) findViewById(R.id.ListView01);
    list.setClickable(true);

    final List<Phonebook> listOfPhonebook = new ArrayList<Phonebook>();
    PhonebookAdapterView adapter = new PhonebookAdapterView(this, listOfPhonebook);

    list.setAdapter(adapter);

    try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */
         InputSource is = new InputSource(getResources().openRawResource(R.raw.example));

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(is.getByteStream()));

    } catch (Exception e) {
        System.out.println("XML Parsing Exception = " + e);
    }


    phonebook = MyXMLHandler.phonebook;
    list.setAdapter(adapter);

xml 处理程序

    Boolean currentElement = false;
    String currentValue = null;
    public static Phonebook phonebook = null;

    public static Phonebook getPhonebook() {
        return phonebook;
    }

    public static void setPhonebook(Phonebook p) {
        MyXMLHandler.phonebook = p;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            phonebook = new Phonebook();
        }
    }

    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
     * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("name"))
            phonebook.setName(currentValue);
        else if (localName.equalsIgnoreCase("phone"))
            phonebook.setPhone(currentValue);
        else if (localName.equalsIgnoreCase("Mail"))
            phonebook.setMail(currentValue);

    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

和适配器视图,这与它是一个简单的列表视图文件时相同。但我不确定如何考虑 xml。

公共类 PhonebookAdapterView 扩展 BaseAdapter {

private Context context;
private List<Phonebook> phonebook;

 public PhonebookAdapterView(Context theContext, List<Phonebook> theListPhonebook) {
        context = theContext;
        phonebook = theListPhonebook;
    }


@Override
public int getCount() {
    return phonebook.size();
}
@Override
public Object getItem(int position) {
    return phonebook.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
     Phonebook entry = phonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.phone_row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.tvContact);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.tvMobile);
        tvPhone.setText(entry.getPhone());

        TextView tvMail = (TextView) convertView.findViewById(R.id.tvMail);
        tvMail.setText(entry.getMail());

      return convertView;
}

}

编辑

MyXMLHAndler

公共类 MyXMLHandler 扩展 DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static List<Phonebook> phonebook = new ArrayList<Phonebook>();

    public static List<Phonebook> getPhonebook() {
        return phonebook;
    }

    public static void setPhonebook(List<Phonebook> p) {
        MyXMLHandler.phonebook = p;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            phonebook = new ArrayList<Phonebook>();
        }
    }

    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
     * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("name"))
            ((Phonebook) phonebook).setName(currentValue);
        else if (localName.equalsIgnoreCase("phone"))
            ((Phonebook) phonebook).setPhone(currentValue);
        else if (localName.equalsIgnoreCase("Mail"))
            ((Phonebook) phonebook).setMail(currentValue);

    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

第二次编辑

public List<Phonebook> phonebook = new ArrayList<Phonebook>();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView list = (ListView) findViewById(R.id.ListView01);
    list.setClickable(true);

    final List<Phonebook> listOfPhonebook = MyXMLHandler.getPhonebook();
    PhonebookAdapterView adapter = new PhonebookAdapterView(this, listOfPhonebook);
    list.setAdapter(adapter);

    try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */
         InputSource is = new InputSource(getResources().openRawResource(R.raw.example));

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(is.getByteStream()));

    } catch (Exception e) {
        System.out.println("XML Parsing Exception = " + e);
    }  

XMLHandler

    public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public  List<Phonebook> phonebook = new ArrayList<Phonebook>();

    public List<Phonebook> getPhonebook() {
        return phonebook;
    }

    public void setPhonebook(List<Phonebook> p) {
        phonebook = p;
    }

    int entryCount;

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            Phonebook pb = new Phonebook();
            getPhonebook().add(pb);
            entryCount++;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
  /** set value */
         if (localName.equalsIgnoreCase("name"))
                ((Phonebook)phonebook.get(entryCount)).setName(currentValue);
            if (localName.equalsIgnoreCase("phone"))
                ((Phonebook)phonebook.get(entryCount)).setPhone(currentValue);
            if (localName.equalsIgnoreCase("Mail"))
                ((Phonebook)phonebook.get(entryCount)).setMail(currentValue);
}


    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

I am in the middle of converting a listview example into a program that operates by reading an xml file and then populate a list view with its contents. I seem to have hit a snag though. I'm not sure what to do with the Adapter I made for the first example and how to use it in this new program, any pointers would be appreciated.
Heres the main

Phonebook phonebook = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView list = (ListView) findViewById(R.id.ListView01);
    list.setClickable(true);

    final List<Phonebook> listOfPhonebook = new ArrayList<Phonebook>();
    PhonebookAdapterView adapter = new PhonebookAdapterView(this, listOfPhonebook);

    list.setAdapter(adapter);

    try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */
         InputSource is = new InputSource(getResources().openRawResource(R.raw.example));

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(is.getByteStream()));

    } catch (Exception e) {
        System.out.println("XML Parsing Exception = " + e);
    }


    phonebook = MyXMLHandler.phonebook;
    list.setAdapter(adapter);

Heres the xml handler

    Boolean currentElement = false;
    String currentValue = null;
    public static Phonebook phonebook = null;

    public static Phonebook getPhonebook() {
        return phonebook;
    }

    public static void setPhonebook(Phonebook p) {
        MyXMLHandler.phonebook = p;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            phonebook = new Phonebook();
        }
    }

    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
     * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("name"))
            phonebook.setName(currentValue);
        else if (localName.equalsIgnoreCase("phone"))
            phonebook.setPhone(currentValue);
        else if (localName.equalsIgnoreCase("Mail"))
            phonebook.setMail(currentValue);

    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

And the adapter view, which is the same back when it was a simple listview file. Im not sure how to factor in xml though.

public class PhonebookAdapterView extends BaseAdapter {

private Context context;
private List<Phonebook> phonebook;

 public PhonebookAdapterView(Context theContext, List<Phonebook> theListPhonebook) {
        context = theContext;
        phonebook = theListPhonebook;
    }


@Override
public int getCount() {
    return phonebook.size();
}
@Override
public Object getItem(int position) {
    return phonebook.get(position);
}
@Override
public long getItemId(int position) {
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
     Phonebook entry = phonebook.get(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.phone_row, null);
        }
        TextView tvContact = (TextView) convertView.findViewById(R.id.tvContact);
        tvContact.setText(entry.getName());

        TextView tvPhone = (TextView) convertView.findViewById(R.id.tvMobile);
        tvPhone.setText(entry.getPhone());

        TextView tvMail = (TextView) convertView.findViewById(R.id.tvMail);
        tvMail.setText(entry.getMail());

      return convertView;
}

}

EDIT

MyXMLHAndler

public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public static List<Phonebook> phonebook = new ArrayList<Phonebook>();

    public static List<Phonebook> getPhonebook() {
        return phonebook;
    }

    public static void setPhonebook(List<Phonebook> p) {
        MyXMLHandler.phonebook = p;
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            phonebook = new ArrayList<Phonebook>();
        }
    }

    /** Called when tag closing ( ex:- <name>AndroidPeople</name>
     * -- </name> )*/
    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {

        currentElement = false;

        /** set value */
        if (localName.equalsIgnoreCase("name"))
            ((Phonebook) phonebook).setName(currentValue);
        else if (localName.equalsIgnoreCase("phone"))
            ((Phonebook) phonebook).setPhone(currentValue);
        else if (localName.equalsIgnoreCase("Mail"))
            ((Phonebook) phonebook).setMail(currentValue);

    }

    /** Called to get tag characters ( ex:- <name>AndroidPeople</name>
     * -- to get AndroidPeople Character ) */
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

}

Second Edit

public List<Phonebook> phonebook = new ArrayList<Phonebook>();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ListView list = (ListView) findViewById(R.id.ListView01);
    list.setClickable(true);

    final List<Phonebook> listOfPhonebook = MyXMLHandler.getPhonebook();
    PhonebookAdapterView adapter = new PhonebookAdapterView(this, listOfPhonebook);
    list.setAdapter(adapter);

    try {

        /** Handling XML */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        /** Send URL to parse XML Tags */
         InputSource is = new InputSource(getResources().openRawResource(R.raw.example));

        /** Create handler to handle XML Tags ( extends DefaultHandler ) */
        MyXMLHandler myXMLHandler = new MyXMLHandler();
        xr.setContentHandler(myXMLHandler);
        xr.parse(new InputSource(is.getByteStream()));

    } catch (Exception e) {
        System.out.println("XML Parsing Exception = " + e);
    }  

XMLHandler

    public class MyXMLHandler extends DefaultHandler {

    Boolean currentElement = false;
    String currentValue = null;
    public  List<Phonebook> phonebook = new ArrayList<Phonebook>();

    public List<Phonebook> getPhonebook() {
        return phonebook;
    }

    public void setPhonebook(List<Phonebook> p) {
        phonebook = p;
    }

    int entryCount;

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {

        currentElement = true;

        if (localName.equals("maintag"))
        {
            /** Start */
            Phonebook pb = new Phonebook();
            getPhonebook().add(pb);
            entryCount++;
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
  /** set value */
         if (localName.equalsIgnoreCase("name"))
                ((Phonebook)phonebook.get(entryCount)).setName(currentValue);
            if (localName.equalsIgnoreCase("phone"))
                ((Phonebook)phonebook.get(entryCount)).setPhone(currentValue);
            if (localName.equalsIgnoreCase("Mail"))
                ((Phonebook)phonebook.get(entryCount)).setMail(currentValue);
}


    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {

        if (currentElement) {
            currentValue = new String(ch, start, length);
            currentElement = false;
        }

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一口甜 2025-01-03 16:28:55

要使其发挥作用,需要做很多事情。

首先,您必须通过读取 XML 文件来创建电话簿列表
并将数据放入 MyXMLHandler 类的 List 中

public static Phonebook phonebook = null;

应该

public static List<Phonebook> phonebook = new ArrayList<Phonebook>();

在您的 XMLHandler 类中进行相应的填充
然后您将此列表设置到适配器中 -

MyAdapter.setList(phonebook); // your method inside adapter

然后您将使用此列表中的电话簿对象
在您的 getView() 类中填充 TextView 并 addView(TextView) 它们
进入您的 ConvertView 对象并返回它。

我在这篇文章中制作了一个示例列表应用程序 我如何选择和杀死多个应用程序
或者有很多关于如何创建列表视图的帖子。

更新:

在您的 XMLHandler 类中
从电话簿中删除静态 public static List;电话簿 以及
从 set/getPhonebook() 方法开始
您正在新建该类并在活动类中使用 myXMLHandler.getPhonebook();

假设您有以下 xml

<phonebook>
<entry>
<name>abc</name>
<phone>def</phone>
<mail>ghi</mail>
</entry>
<entry>
<name>abc1</name>
<phone>def2</phone>
<mail>ghi3</mail>
</entry>
</phonebook>

工作代码:

import android.app.Activity;
import android.content.Context;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;
import java.util.List;

public class ListActivity extends Activity {


    ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ll = new LinearLayout(this);
        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        ll.setLayoutParams(lp1);
        ll.setOrientation(1);
        lv = new ListView(this);
        MyXMLHandler myXMLHandler = readXML();

        List<Phonebook> listOfPhonebook = myXMLHandler.getPhonebook();
        //adapter = new TaskListAdapter(this);
        MyListAdapter adapter = new MyListAdapter(this, listOfPhonebook);
        lv.setAdapter(adapter);
        ll.addView(lv);

        setContentView(ll);

    }

    private MyXMLHandler readXML() {
        MyXMLHandler myXMLHandler = null;
        try {

            /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            /** Send URL to parse XML Tags */
            InputSource is = new InputSource(getResources().openRawResource(R.raw.a));

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(is.getByteStream()));

        } catch (Exception e) {
            System.out.println("XML Parsing Exception = " + e);
        }
        return myXMLHandler;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    class MyListAdapter extends BaseAdapter {

        private static final String TAG = "TaskListAdapter";


        List<Phonebook> phonebook;
        Context context;

        public MyListAdapter(Context context, List<Phonebook> phonebook) {
            this.phonebook = phonebook;
            Log.d(TAG, "created new task list adapter");
            this.context = context;
        }

        public int getCount() {
            return phonebook.size();
        }

        public Phonebook getItem(int position) {
            return phonebook.get(position);
        }

        public long getItemId(int position) {
            return position;
        }


        public View getView(final int position, View convertView, ViewGroup parent) {
            RelativeLayout rl = new RelativeLayout(context);
            TextView textPid = new TextView(context);
            textPid.setId(222222);
            textPid.setText(getItem(position).getName());

            TextView textName = new TextView(context);
            textName.setId(333333);
            textName.setText(getItem(position).getEmail());


            TextView textEmail = new TextView(context);
            textEmail.setId(444444);
            textEmail.setText(getItem(position).getEmail());

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            lp.setMargins(1, 0, 0, 0);
            rl.addView(textName, lp);

            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.RIGHT_OF, textName.getId());
            lp1.setMargins(1, 0, 0, 0);
            rl.addView(textPid, lp1);


            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp2.addRule(RelativeLayout.RIGHT_OF, textPid.getId());
            lp2.setMargins(1, 0, 0, 0);
            rl.addView(textEmail, lp2);


            return rl;
        }

    }

    class MyXMLHandler extends DefaultHandler {

        Boolean currentElement = false;
        String currentValue = null;
        public List<Phonebook> phonebook = new ArrayList<Phonebook>();
        int entryCount = 0;

        public List<Phonebook> getPhonebook() {
            return phonebook;
        }

        public void setPhonebook(List<Phonebook> p) {
            phonebook = p;
        }


        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            currentElement = true;

            if (localName.equals("entry")) {
                /** Start */
                Phonebook pb = new Phonebook();
                getPhonebook().add(pb);

            }
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            /** set value */
            if (localName.equalsIgnoreCase("name"))
                (phonebook.get(entryCount)).setName(currentValue);
            if (localName.equalsIgnoreCase("phone"))
                (phonebook.get(entryCount)).setPhone(currentValue);
            if (localName.equalsIgnoreCase("mail"))
                (phonebook.get(entryCount)).setEmail(currentValue);

            if (localName.equalsIgnoreCase("entry")) entryCount++;
        }


        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {

            if (currentElement) {
                currentValue = new String(ch, start, length);
                currentElement = false;
            }

        }

    }

}

There're quite a few things to do to make it work.

First of all you will have to create your phonebook list by reading an XML file
and putting a data into a List of the MyXMLHandler class
your

public static Phonebook phonebook = null;

should be

public static List<Phonebook> phonebook = new ArrayList<Phonebook>();

and populated accordingly within your XMLHandler class
and after that you set this list into your adapter -

MyAdapter.setList(phonebook); // your method inside adapter

Then you're using the Phonebook objects from this list
within your getView() class to populate your TextViews and addView(TextView) them
into your ConvertView object and return it.

I've made an example list application in this post how can i select and kill multiple application
or there's a bunch of posts on how to create a listview.

UPDATED:

in your XMLHandler class
Remove the statics from phonebook public static List<Phonebook> phonebook as well
as from the set/getPhonebook() methods
you are NEWing the class and use the myXMLHandler.getPhonebook(); in your activity class.

assuming you have the following xml

<phonebook>
<entry>
<name>abc</name>
<phone>def</phone>
<mail>ghi</mail>
</entry>
<entry>
<name>abc1</name>
<phone>def2</phone>
<mail>ghi3</mail>
</entry>
</phonebook>

Working code:

import android.app.Activity;
import android.content.Context;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;
import java.util.List;

public class ListActivity extends Activity {


    ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LinearLayout ll = new LinearLayout(this);
        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        ll.setLayoutParams(lp1);
        ll.setOrientation(1);
        lv = new ListView(this);
        MyXMLHandler myXMLHandler = readXML();

        List<Phonebook> listOfPhonebook = myXMLHandler.getPhonebook();
        //adapter = new TaskListAdapter(this);
        MyListAdapter adapter = new MyListAdapter(this, listOfPhonebook);
        lv.setAdapter(adapter);
        ll.addView(lv);

        setContentView(ll);

    }

    private MyXMLHandler readXML() {
        MyXMLHandler myXMLHandler = null;
        try {

            /** Handling XML */
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            XMLReader xr = sp.getXMLReader();

            /** Send URL to parse XML Tags */
            InputSource is = new InputSource(getResources().openRawResource(R.raw.a));

            /** Create handler to handle XML Tags ( extends DefaultHandler ) */
            myXMLHandler = new MyXMLHandler();
            xr.setContentHandler(myXMLHandler);
            xr.parse(new InputSource(is.getByteStream()));

        } catch (Exception e) {
            System.out.println("XML Parsing Exception = " + e);
        }
        return myXMLHandler;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    class MyListAdapter extends BaseAdapter {

        private static final String TAG = "TaskListAdapter";


        List<Phonebook> phonebook;
        Context context;

        public MyListAdapter(Context context, List<Phonebook> phonebook) {
            this.phonebook = phonebook;
            Log.d(TAG, "created new task list adapter");
            this.context = context;
        }

        public int getCount() {
            return phonebook.size();
        }

        public Phonebook getItem(int position) {
            return phonebook.get(position);
        }

        public long getItemId(int position) {
            return position;
        }


        public View getView(final int position, View convertView, ViewGroup parent) {
            RelativeLayout rl = new RelativeLayout(context);
            TextView textPid = new TextView(context);
            textPid.setId(222222);
            textPid.setText(getItem(position).getName());

            TextView textName = new TextView(context);
            textName.setId(333333);
            textName.setText(getItem(position).getEmail());


            TextView textEmail = new TextView(context);
            textEmail.setId(444444);
            textEmail.setText(getItem(position).getEmail());

            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

            lp.setMargins(1, 0, 0, 0);
            rl.addView(textName, lp);

            RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp1.addRule(RelativeLayout.RIGHT_OF, textName.getId());
            lp1.setMargins(1, 0, 0, 0);
            rl.addView(textPid, lp1);


            RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp2.addRule(RelativeLayout.RIGHT_OF, textPid.getId());
            lp2.setMargins(1, 0, 0, 0);
            rl.addView(textEmail, lp2);


            return rl;
        }

    }

    class MyXMLHandler extends DefaultHandler {

        Boolean currentElement = false;
        String currentValue = null;
        public List<Phonebook> phonebook = new ArrayList<Phonebook>();
        int entryCount = 0;

        public List<Phonebook> getPhonebook() {
            return phonebook;
        }

        public void setPhonebook(List<Phonebook> p) {
            phonebook = p;
        }


        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

            currentElement = true;

            if (localName.equals("entry")) {
                /** Start */
                Phonebook pb = new Phonebook();
                getPhonebook().add(pb);

            }
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            /** set value */
            if (localName.equalsIgnoreCase("name"))
                (phonebook.get(entryCount)).setName(currentValue);
            if (localName.equalsIgnoreCase("phone"))
                (phonebook.get(entryCount)).setPhone(currentValue);
            if (localName.equalsIgnoreCase("mail"))
                (phonebook.get(entryCount)).setEmail(currentValue);

            if (localName.equalsIgnoreCase("entry")) entryCount++;
        }


        @Override
        public void characters(char[] ch, int start, int length)
                throws SAXException {

            if (currentElement) {
                currentValue = new String(ch, start, length);
                currentElement = false;
            }

        }

    }

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文