java - Android/Java - ListView 使用 ArrayList 填充 XML 数据 : Only Displays First Item

标签 java android arrays android-listview arraylist

我正在尝试使用 ArrayList 用 XML 数据填充 ListView - 到目前为止我已经能够完成 - 问题是 ArrayList 似乎没有用超出第一个项目的数据填充 ListView listView,我不确定为什么。

截图

enter image description here

XML 数据:

此 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>

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/xml.php?cmd=getVideos&username=fake&password=";
    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);

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

命令.java

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

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

    @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;
    }

}

SAXMLParser.java

public class SAXXMLParser {

    public static List<Cmd> parse(InputStream is) {
        List<Cmd> response = null;
        try {
            // create a XMLReader from SAXParser
            XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
                    .getXMLReader();
            // create a SAXXMLHandler
            SAXXMLHandler saxHandler = new SAXXMLHandler();
            // store handler in XMLReader
            xmlReader.setContentHandler(saxHandler);
            // the process starts
            xmlReader.parse(new InputSource(is));
            // get the `Video list`
            response = saxHandler.getResponse();

        } catch (Exception ex) {
            Log.d("XML", "SAXXMLParser: parse() failed");
            ex.printStackTrace();
        }

        // return video list
        return response;
    }
}

SAXMLHandler.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("cmd")) {
            // 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
            videos.add(cmd);
        } 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);

        }
    }
}

parser_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

     <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/button" />

     <ListView
        android:id="@+id/cmdList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       />
</LinearLayout>

XML 截图

enter image description here

附言

如果需要任何其他信息 - 请告诉我(接下来的几个小时我会在办公 table 前处理此问题,很乐意回答任何问题并及时接受任何答案)

最佳答案

SAXMLHandler.javaendElement() 中如果qName.equalsIgnoreCase("videos"),您只将命令添加到视频列表的方法.

在所有其他情况下,您修改了 cmd 但实际上并未将其添加到列表中。你想添加一个 videos.add(cmd) else if 中的声明 block 以及所有 cmd 都被添加到列表中。

这里的这个错误是您的 List<Cmd> videos 的原因只有一个项目,因此在您的 ListView 中只显示一个项目。

关于java - Android/Java - ListView 使用 ArrayList 填充 XML 数据 : Only Displays First Item,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21609224/

相关文章:

java-mysql数据检索问题

java - 当之前定义相等时,使两个列表不相等

java - 膨胀 View 会在物理设备上抛出 Resources$NotFoundException

arrays - 按类型过滤 Swift [AnyObject] 数组

javascript - 在 for 循环中设置对象值,然后推送到数组会导致所有最终数组项具有相同的值

java - 为什么 Tomcat 在 catalina.out 日志文件中将我的日志行加倍?

java - 从 ArrayList 创建默认表

带有 map 数组的 HTML 表单

android - 从静态方法调用 finish()

android - 索尼智能 watch 2 : need to change supportsLowPowerMode() at runtime