【问题标题】:Android: Simple XML SAX Parser - Displays Same Data Over and OverAndroid:简单的 XML SAX 解析器 - 一遍又一遍地显示相同的数据
【发布时间】:2014-02-06 21:42:44
【问题描述】:

我创建了一个 XML 解析器,它使用从 XML 文件中获取的数据填充 listView。问题是由于某种原因,listView 一遍又一遍地显示相同的数据,而不是每个 listView 项的唯一数据。

我不确定究竟是什么导致了这个问题 - 非常感谢任何见解。

截图:

XML 数据:

<response>
<cmd>getVideos</cmd>
<success>1</success>
<NumberOfVideos>4</NumberOfVideos>
<Videos>
<Video>
<VideoName>sample_iPod</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_mpeg4</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_sorenson</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
</VideoUrl>
<VideoTags/>
</Video>
<Video>
<VideoName>sample_iTunes</VideoName>
<VideoDesc/>
<VideoUrl>
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
</VideoUrl>
<VideoTags/>
</Video>
</Videos>
</response>

示例/教程:

http://theopentutorials.com/tutorials/android/xml/android-simple-xml-sax-parser-tutorial/

SAXXMLHandler.java

     public class SAXXMLHandler extends DefaultHandler {
    private List<Cmd> videos;
    private String tempVal;
    // to maintain context
    private Cmd cmd;

    public SAXXMLHandler() {
        videos = new ArrayList<Cmd>();
    }

    public List<Cmd> getResponse() {
        return videos;
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equalsIgnoreCase("Video")) {
            // create a new instance of cmd
            cmd = new Cmd();

        }
    }

    public void characters(char[] ch, int start, int length)
            throws SAXException {
        tempVal = new String(ch, start, length);
    }

    public void endElement(String uri, String localName, String qName)
            throws SAXException {
  if (qName.equalsIgnoreCase("videos")) {
            // add it to the list
        } else if (qName.equalsIgnoreCase("success")) {
            cmd.setSuccess(tempVal);
        } else if (qName.equalsIgnoreCase("numberofvideos")) {
            cmd.setNumberOfVideos(tempVal);
        } else if (qName.equalsIgnoreCase("videos")) {
            cmd.setVideos(videos);
        } else if (qName.equalsIgnoreCase("video")) {
            cmd.setVideo(tempVal);
        } else if (qName.equalsIgnoreCase("videoname")) {
            cmd.setVideoName(tempVal);
        } else if (qName.equalsIgnoreCase("videourl")) {
            cmd.setVideoURL(tempVal);
            videos.add(cmd); //You only need store an instance of your Cmd 
        }
      }
    }

CustomListViewAdapter.java

public class CustomListViewAdapter extends ArrayAdapter<Cmd> {
    Activity context;
    List<Cmd> videos;

    public CustomListViewAdapter(Activity context, List<Cmd> videos) {
        super(context, R.layout.list_item2, videos);
        this.context = context;
        this.videos = videos;
    }

    /*private view holder class*/
    private class ViewHolder {
        ImageView imageView;
        TextView txtSuccess;
        TextView txtCmd;
        TextView txtPrice;
    }

    public Cmd getItem(int position) {
        return videos.get(position);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = context.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item2, null);
            holder = new ViewHolder();
            holder.txtSuccess = (TextView) convertView.findViewById(R.id.success);
            holder.txtCmd = (TextView) convertView.findViewById(R.id.cmd);
            holder.txtPrice = (TextView) convertView.findViewById(R.id.price);
            holder.imageView = (ImageView) convertView.findViewById(R.id.thumbnail);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Cmd cmd = (Cmd) getItem(position);


        holder.txtSuccess.setText(cmd.getSuccess());
            holder.txtCmd.setText(cmd.getCmd());
         //   holder.imageView.setImageBitmap(cmd.getImageBitmap());
            holder.txtPrice.setText(cmd.getVideoName() + "");

        return convertView;
    }
}

SAXParserAsyncTaskActivity.java

public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {
    Button button;
    ListView listView;
    List<Cmd> videos = new ArrayList<Cmd>();

    CustomListViewAdapter listViewAdapter;

    static final String URL = "http://mobile.example.com/api/xmlrpc.php?cmd=getVideos&username=fake&password=credential";
    public static final String LIBRARY = "Library";

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.parser_main);

        findViewsById();
        button.setOnClickListener(this);
        listView.setOnItemClickListener(this);

        GetXMLTask task = new GetXMLTask(this);
        task.execute(new String[] { URL });
    }

    private void findViewsById() {
        button = (Button) findViewById(R.id.button);
        listView = (ListView) findViewById(R.id.cmdList);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
    }

    @Override
    public void onClick(View view) {
        // GetXMLTask task = new GetXMLTask(this);
        // task.execute(new String[] { URL });
    }

    // private inner class extending AsyncTask
    private class GetXMLTask extends AsyncTask<String, Void, List<Cmd>> {
        private Activity context;

        public GetXMLTask(Activity context) {
            this.context = context;
        }


        protected void onPostExecute(List<Cmd> videos) {
            listViewAdapter = new CustomListViewAdapter(context, videos);
            listView.setAdapter(listViewAdapter);
        }

        /*
         * uses HttpURLConnection to make Http request from Android to download
         * the XML file
         */
        private String getXmlFromUrl(String urlString) {
            StringBuffer output = new StringBuffer("");
            try {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();

                    BufferedReader buffer = new BufferedReader(
                            new InputStreamReader(stream));
                    String s = "";
                    while ((s = buffer.readLine()) != null)
                        output.append(s);
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return output.toString();
        }

        @Override
        protected List<Cmd> doInBackground(String... urls) {
            List<Cmd> videos = null;
            String xml = null;
            for (String url : urls) {
                xml = getXmlFromUrl(url);

                InputStream stream = new ByteArrayInputStream(xml.getBytes());
                videos = SAXXMLParser.parse(stream);

if ( videos == null) {
                Toast.makeText(getApplicationContext(), "Videos is null!)",
                           Toast.LENGTH_LONG).show();

            }
                for (Cmd cmd : videos) {
                    String videoName = cmd.getVideoName();
                    // String getVideos = cmd.getVideos();
//                    String getVideo = cmd.getVideo();
//                    String getVideoURL = cmd.getVideoURL();
//                    String getNumberOfVideos = cmd.getNumberOfVideos();
//
//                    Bitmap bitmap = null;
//                    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
//                    bmOptions.inSampleSize = 1;
//
//                    try {
//                        bitmap = BitmapFactory.decodeStream(
//                                new URL(videoName).openStream(), null,
//                                bmOptions);
//                    } catch (MalformedURLException e) {
//                        e.printStackTrace();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
                }
            }
            // stream.close();
            return videos;
        }
    }
}

【问题讨论】:

  • 当元素的名称为“cmd”时,您似乎只创建了一个cmd 实例,然后一遍又一遍地添加它。
  • 有什么理由在 startElement() 而不是 endElement() 中创建 cmd?如果 new cmd() 发生在 endElement 中,代码会更清晰(您不需要成员变量——它将是本地的)这将使您在需要时忘记创建新变量的可能性大大降低。
  • @323go - 我怎样才能避免这样做并每次都创建一个独特的项目?
  • @DaleWilson - 我应该像这样在开头添加它,对吗? public void endElement(String uri, String localName, String qName) throws SAXException { cmd = new Cmd();
  • 你可以听从@Elenasys 的建议,他扩展了我的评论。

标签: java android xml listview sax


【解决方案1】:

您只创建了一个覆盖自身的Cmd() 实例,因为您只有一个&lt;cmd&gt; 元素。

变化:

 if (qName.equalsIgnoreCase("cmd")) {
            // create a new instance of cmd
            cmd = new Cmd();

        }

到:

 if (qName.equalsIgnoreCase("Video")) {
            // create a new instance of cmd
            cmd = new Cmd();

        }

当您的解析器读取每个&lt;Video&gt; 元素时,您需要创建Cmd() 的实例。

并将您的 endElement(String uri, String localName, String qName) 方法更改为:

  public void endElement(String uri, String localName, String qName)
            throws SAXException {
  if (qName.equalsIgnoreCase("videos")) {
            // add it to the list
        /*} else if (qName.equalsIgnoreCase("success")) {
            cmd.setSuccess(tempVal);
        } else if (qName.equalsIgnoreCase("numberofvideos")) {
            cmd.setNumberOfVideos(tempVal);
        } else if (qName.equalsIgnoreCase("videos")) {
            cmd.setVideos(videos);
        } else if (qName.equalsIgnoreCase("video")) {
            cmd.setVideo(tempVal);*/
        } else if (qName.equalsIgnoreCase("videoname")) {
            cmd.setVideoName(tempVal);
        } else if (qName.equalsIgnoreCase("videourl")) {
            cmd.setVideoURL(tempVal);
            videos.add(cmd); //You only need store an instance of your Cmd 
        }
      }

【讨论】:

  • 它现在在线崩溃:for (Cmd cmd : videos) { 在 SAXParserAsyncTaskActivity 中(在进行了上面建议的更改之后)
  • 您的 Wifi 又关闭了吗?正如人们之前所说,您必须先测试videos 是否为空,然后再尝试使用它。
  • #Fail(是的 - 它是)好的。所以现在它正在工作......有点(listView 中的每个第 3 个项目显示 VideoName 所有其他项目都显示为 null )
  • 好的,我的朋友。从现在开始,我将忽略您的问题,除非您在尝试使用它之前检查videos == null,并对捕获的异常执行某些操作,而不是打印堆栈跟踪并忽略它。对不起,但如果你不接受建议,我不准备提供它。玩得开心,祝你好运。
  • 在你的 doInBackground() 方法中不需要这个“for (String url : urls) {”,你只使用一个 .xml
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-20
  • 2017-02-15
  • 2019-08-29
相关资源
最近更新 更多