使用xmlpullparser解析xml时在列表中获取相同的值

时间:2014-02-23 13:54:04

标签: java android xml-parsing

我正在尝试解析资产文件夹中存在的xml文件。所有似乎都很好并且没有错误,但问题是它为xml中的每个节点给列表提供了相同的值。我认为它会覆盖以前的值。我被困在这里。即使经过大量的谷歌搜索无法找到任何解决方案。任何帮助将不胜感激。

以下是代码: -

Product.java

package com.example.webservicedemo;

public class product {


    private static String productname="";
    private static String productcolor="";
    private static String productquantity="";



    public static String getProductname() {
        return productname;
    }
    public static void setProductname(String productname) {
        product.productname = productname;
    }
    public static String getProductcolor() {
        return productcolor;
    }
    public static void setProductcolor(String productcolor) {
        product.productcolor = productcolor;
    }
    public static String getProductquantity() {
        return productquantity;
    }
    public static void setProductquantity(String productquantity) {
        product.productquantity = productquantity;
    }
}

以下是解析器的代码: - 的 productXmlPullParser.java

package com.example.webservicedemo;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.AssetManager;
import android.widget.Toast;
import com.example.webservicedemo.*;
public class productXmlPullParser {

    static final String KEY_PRODUCT = "product";
    static final String KEY_NAME = "productname";
    static final String KEY_COLOR = "productcolor";
    static final String KEY_QUANTITY = "productquantity";


    public static List<product> getproductsFromFile(Context ctx) {
        String tagname;
        List<product> Products;
        Products = new ArrayList<product>();

        product curproduct = null;
        String curText = "";
        InputStream is = null;
        try {
            is = ctx.getAssets().open("temp.xml");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();

        }


        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xpp = factory.newPullParser();


            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            xpp.setInput(reader);

            int eventType = xpp.getEventType();

            while (eventType != XmlPullParser.END_DOCUMENT) {
                 tagname = xpp.getName();

                switch (eventType) {
                case XmlPullParser.START_TAG:
                    if (tagname.equalsIgnoreCase(KEY_PRODUCT)) {

                        curproduct = new product();
                    }
                    break;

                case XmlPullParser.TEXT:
                    //grab the current text so we can use it in END_TAG event
                    curText = xpp.getText();


                    break;

                case XmlPullParser.END_TAG:

                    if (tagname.equalsIgnoreCase(KEY_PRODUCT)) {
                        // if </site> then we are done with current Site
                        // add it to the list.
                        Products.add(curproduct);
//                      Toast.makeText(ctx, curproduct+"",3000).show();

                    } else if (tagname.equalsIgnoreCase(KEY_NAME)) {
                        // if </name> use setName() on curSite
                        product.setProductname(curText);
                        Toast.makeText(ctx, curText+"",3000).show();

                    } else if (tagname.equalsIgnoreCase(KEY_COLOR)) {
                        // if </link> use setLink() on curSite
                        curproduct.setProductcolor(curText);
                        Toast.makeText(ctx, curText+"",3000).show();
                    } else if (tagname.equalsIgnoreCase(KEY_QUANTITY)) {
                        // if </about> use setAbout() on curSite
                        curproduct.setProductquantity(curText);
                        Toast.makeText(ctx, curText+"",3000).show();

                    } 

                    break;

                default:
                    break;
                }
                //move on to next iteration
                eventType = xpp.next();
            }

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(ctx, "error", 6000).show();
        }

        // return the populated list.
        return Products;
    }
}

以下是我的自定义arrayadapter的代码: -

ProductAdapter

    package com.example.webservicedemo;

    import java.util.List;

    import android.content.Context;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.RelativeLayout;
    import android.widget.TextView;



    public class UsersAdapter extends ArrayAdapter<product> {

        public UsersAdapter(Context context, int resource, List<product> objects) {
            super(context, resource, objects);
            // TODO Auto-generated constructor stub
        }


        @Override
        public View getView(int pos, View convertView, ViewGroup parent){
            RelativeLayout row = (RelativeLayout)convertView;
            Log.i("Users", "getView pos = " + pos);
            if(null == row){
                LayoutInflater inflater = (LayoutInflater)parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = (RelativeLayout)inflater.inflate(R.layout.listitem, null);
            }

            TextView Email = (TextView)row.findViewById(R.id.txtEmail);
            TextView Password = (TextView)row.findViewById(R.id.txtPassword);
            TextView Deviceid = (TextView)row.findViewById(R.id.txtDeviceid);
            Email.setText(getItem(pos).getProductname());
            Password.setText(getItem(pos).getProductcolor());
            Deviceid.setText(getItem(pos).getProductquantity());

            return row;

        }

    }

以下是我尝试在列表中获取结果值的主要活动

MainActivity.java

package com.example.webservicedemo;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import com.example.webservicedemo.productXmlPullParser;;;

public class UserList extends Activity {
UsersAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xmlparsingdemo);


        ListView lvUser=(ListView)findViewById(R.id.lvUsers);
        mAdapter=new UsersAdapter(getApplicationContext(),R.layout.listitem,productXmlPullParser.getproductsFromFile(getApplicationContext()));
        lvUser.setAdapter(mAdapter);
        Toast.makeText(getApplicationContext(), mAdapter.getCount()+"",3000).show();

    }
}

这是我要解析的xml: -

temp.xml

<?xml version="1.0" encoding="UTF-8"?>
<products>
    <product>     
        <productname>Jeans</productname>
        <productcolor>red</productcolor>
        <productquantity>5</productquantity>
    </product>
    <product>     
        <productname>Tshirt</productname>
        <productcolor>blue</productcolor>
        <productquantity>3</productquantity>
    </product>
    <product>     
        <productname>shorts</productname>
        <productcolor>green</productcolor>
        <productquantity>4</productquantity>
    </product>

</products>

但是输出就像下面的截图: -

enter image description here

经过很多努力,我找不到出错的地方。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

你的班级“产品”中的问题。字段是静态的,每个字段包含所有实例的最后一个值。删除“静态”修改器,一切都会正常工作。