java - Android XML 解析器显示重复数据

标签 java android xml sax saxparser

我已经为 android 构建了一个基于 SAX 的 XML 解析器,但是当我尝试执行它时,我得到了重复的数据。我不确定我到底做错了什么(我以前也遇到过类似的问题,问题出在线路上的问题: if (qName.equalsIgnoreCase("Video")) {但是我已经多次查看了代码,所以我不确定我能做什么来解决这个问题,或者如何防止重复的数据。

屏幕截图

enter image description here

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("videos")) {
            cmd.setSuccess(tempVal);            
        } else if (qName.equalsIgnoreCase("videos")) {
            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 void run() {
        Intent intent = new Intent(context, ViewVideo.class);
        String txt=Cmd.getVideoURL(); 
        intent.putExtra("videofilename", txt);
        context.startActivity(intent);
    }



    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();
        }

        final Cmd cmd = (Cmd) getItem(position);

        holder.txtSuccess.setText(cmd.getVideoName());
        holder.txtSuccess.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                run();
            }
        });
        holder.txtCmd.setText(cmd.getCmd());
        holder.txtCmd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                run();
            }
        });

        holder.txtPrice.setText(cmd.getVideoURL() + "");
        holder.txtPrice.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                run();
            }
        });

        holder.imageView.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                run();
            }
        });
        return convertView;

    }

}

SAXParserAsyncTaskActivity.java

public class SAXParserAsyncTaskActivity extends Activity implements
OnClickListener, OnItemClickListener {

    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=fake";
    public static final String LIBRARY = "Library";

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

        findViewsById();

        listView.setOnItemClickListener(this);

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

    private void findViewsById() {

        listView = (ListView) findViewById(R.id.cmdList);
    }

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

    @Override
    public void onClick(View view) {

    }

    // 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);
        }

        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);

                for (Cmd cmd : videos) {
                    String videoName = cmd.getVideoName();

                }
            }

            return videos;

        }
    }
}

Cmd.java

public class Cmd implements ListAdapter {
    private String success;
    private String cmd;
    List<Cmd> videos;
    private String video;
    private String numberofvideos;
    private static String videoname;
    private static String videourl;
    private LayoutInflater mInflater;
    Button fav_up_btn1;
    Button fav_dwn_btn1;
    Context my_context;

     Bitmap imageBitmap;




    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // If convertView wasn't null it means we have already set it to our
        // list_item_user_video so no need to do it again
        if (convertView == null) {
            // This is the layout we are using for each row in our list
            // anything you declare in this layout can then be referenced below
            convertView = mInflater.inflate(R.layout.list_item_user_video,
                    parent, false);
        }
        // We are using a custom imageview so that we can load images using urls
        ImageView thumb = (ImageView) convertView
                .findViewById(R.id.userVideoThumbImageView);
        //thumb.setScaleType(ScaleType.FIT_XY);
        TextView title = (TextView) convertView
                .findViewById(R.id.userVideoTitleTextView);
        TextView uploader = (TextView) convertView
                .findViewById(R.id.userVideouploaderTextView);

        TextView viewCount = (TextView) convertView
                .findViewById(R.id.userVideoviewsTextView);
        uploader.setText(videos.get(position).getTitle());
        viewCount.setText(videos.get(position).getviewCount() + " views");

        fav_up_btn1 = (Button) convertView.findViewById(R.id.fav_up_btn1);
        fav_up_btn1.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                boolean favIsUp = fav_up_btn1
                        .getBackground()
                        .getConstantState()
                        .equals(my_context.getResources()
                                .getDrawable(R.drawable.fav_up_btn1)
                                .getConstantState());

                // set the background
                fav_up_btn1
                .setBackgroundResource(favIsUp ? R.drawable.fav_dwn_btn1
                        : R.drawable.fav_up_btn1);
            }
        });

        // Get a single video from our list
        final Cmd video = videos.get(position);
        // Set the image for the list item
//  /   thumb.setImageDrawable(video.getThumbUrl());
        //thumb.setScaleType(ScaleType.FIT_XY);
        // Set the title for the list item
        title.setText(video.getTitle());
        uploader.setText("by " + video.getUploader() + " |  ");

        return convertView;
    }

    public String getUploader() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getviewCount() {
        // TODO Auto-generated method stub
        return null;
    }

    public CharSequence getTitle() {
        // TODO Auto-generated method stub
        return null;
    }

    public String getCmd() {
        return cmd;
    }

    public void setCmd(String cmd) {
        this.cmd = cmd;
    }
    public String getSuccess() {
        return success;
    }

    public void setSuccess(String success) {
        this.success = success;
    }

    public String getNumberOfVideos() {
        return numberofvideos;
    }
    public void setNumberOfVideos(String numberofvideos) {
        this.numberofvideos = numberofvideos;
    }
    public List<Cmd> getVideos() {
        return videos;
    }
    public void setVideos(List<Cmd> videos) {
        this.videos = videos;
    }
    public String getVideo() {
        return video;
    }
    public void setVideo(String video) {
        this.video = video;
    }
    public static String getVideoName() {
        return videoname;
    }

    public void setVideoName(String videoname) {
        this.videoname = videoname;
    }
    public static String getVideoURL() {
        return videourl;
    }

    public void setVideoURL(String videourl) {
        this.videourl = videourl;
    }

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

    @Override
    public Object getItem(int position) {
        return videos.get(position);
    }

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

    @Override
    public int getItemViewType(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public int getViewTypeCount() {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public boolean hasStableIds() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isEmpty() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {
        // TODO Auto-generated method stub

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean areAllItemsEnabled() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isEnabled(int position) {
        // TODO Auto-generated method stub
        return false;
    }

    public String getId() {
        // TODO Auto-generated method stub
        return null;
    }



}

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>

最佳答案

1) 您不需要将对象 Cmd 声明为适配器,为什么需要 2 个适配器:P!

2) 您的变量 videonamevideourlstatic!,这就是您获得相同值的原因,更改为:

private String videoname;
private String videourl;

您只需要一个对象Cmd,如下所示:

   public class Cmd {
        private String success;
        private String cmd;
        List<Cmd> videos;
        private String video;
        private String numberofvideos;
        private String videoname;
        private String videourl;

        public String getCmd() {
            return cmd;
        }

        public void setCmd(String cmd) {
            this.cmd = cmd;
        }
        public String getSuccess() {
            return success;
        }

        public void setSuccess(String success) {
            this.success = success;
        }

        public String getNumberOfVideos() {
            return numberofvideos;
        }
        public void setNumberOfVideos(String numberofvideos) {
            this.numberofvideos = numberofvideos;
        }
        public List<Cmd> getVideos() {
            return videos;
        }
        public void setVideos(List<Cmd> videos) {
            this.videos = videos;
        }
        public String getVideo() {
            return video;
        }
        public void setVideo(String video) {
            this.video = video;
        }

        public String getVideoName() {
            return videoname;
        }

        public void setVideoName(String videoname) {
            this.videoname = videoname;
        }
        public String getVideoURL() {
            return videourl;
        }

        public void setVideoURL(String videourl) {
            this.videourl = videourl;
        }

    }

关于java - Android XML 解析器显示重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21688017/

相关文章:

java - AmazonSQSClientBuilder.defaultClient() java.lang.NoSuchFieldError : No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier

java - 使用具有 >> 100k 命中的非常大的查询结果的 JCR。它的规模有多远?

Android 在运行时通过 id 查找资源

android - 尝试了解 android 测试

android - 如何更改 Android 对话框背后的颜色

sql-server - SSIS XML XSLT 任务内存不足

java 通过 XSD 映射到 XML

java - PriorityQueue 比较器类型与 Arrays.sort() 冲突

java - 计算从开始日期到结束日期耗时

java - 通知管理器 : cancel(id) DON'T work