Android/Java-ListView使用ArrayList填充XML数据:仅显示第一项

Android/Java-ListView使用ArrayList填充XML数据:仅显示第一项,java,android,arrays,android-listview,arraylist,Java,Android,Arrays,Android Listview,Arraylist,我试图通过使用ArrayList来填充ListView中的XML数据—到目前为止我已经能够完成—问题是ArrayList似乎没有使用ListView中第一项之外的数据填充ListView,我不确定为什么 截图 XML数据: 此XML文件似乎没有任何与之关联的样式信息。文档树如下所示 <response> <cmd>getVideos</cmd> <success>1</success> <NumberOfVideos>4&

我试图通过使用ArrayList来填充ListView中的XML数据—到目前为止我已经能够完成—问题是ArrayList似乎没有使用ListView中第一项之外的数据填充ListView,我不确定为什么

截图

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>

获取视频
1.
4.
iPod样本
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/06087297988b.m4v
样本mpeg4
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/b5ed9e7100e2.mp4
索伦森样本
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/2a8e64b24997.mov
iTunes示例
http://mobile.example.com/api/wp-content/uploads/sites/6/2014/01/api/1/6c7f65254aad.mov
CustomListViewAdapter.java
公共类CustomListViewAdapter扩展了ArrayAdapter{
活动语境;
列出视频;
公共CustomListViewAdapter(活动上下文、列表视频){
超级(上下文、R.layout.list_item2、视频);
this.context=上下文;
这个。视频=视频;
}
/*私有视图持有者类*/
私有类视窗持有者{
图像视图图像视图;
TextView txtSuccess;
TextView-txtCmd;
TextView txtPrice;
}
public Cmd getItem(int位置){
返回视频。获取(位置);
}
公共视图getView(int位置、视图转换视图、视图组父视图){
视窗座;
LayoutInflater充气器=上下文。getLayoutInflater();
if(convertView==null){
convertView=充气机充气(R.layout.list_item2,空);
holder=新的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.缩略图);
convertView.setTag(支架);
}否则{
holder=(ViewHolder)convertView.getTag();
}
Cmd=(Cmd)getItem(位置);
holder.txtsucture.setText(cmd.getSuccess());
holder.txtCmd.setText(cmd.getCmd());
//holder.imageView.setImageBitmap(cmd.getImageBitmap());
holder.txtPrice.setText(cmd.getVideoName()+);
返回视图;
}
}
SAXParserAsyncTaskActivity.java
公共类SAXParserAsyncTaskActivity扩展活动实现
OnClickListener,OnItemClickListener{
按钮;
列表视图列表视图;
列表视频=新建ArrayList();
自定义listViewAdapter listViewAdapter;
静态最终字符串URL=”http://mobile.example.com/api/xml.php?cmd=getVideos&username=fake&password=";
公共静态最终字符串LIBRARY=“LIBRARY”;
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.parser_main);
findViewsById();
setOnClickListener(此);
setOnItemClickListener(this);
GetXMLTask任务=新的GetXMLTask(此任务);
执行(新字符串[]{URL});
}
私有void findViewsById(){
按钮=(按钮)findViewById(R.id.button);
listView=(listView)findViewById(R.id.cmdList);
}
@凌驾
public void onItemClick(AdapterView父视图、视图、整型位置、,
长id){
}
@凌驾
公共void onClick(视图){
//GetXMLTask任务=新的GetXMLTask(此任务);
//执行(新字符串[]{URL});
}
//私有内部类扩展异步任务
私有类GetXMLTask扩展了AsyncTask{
私人活动语境;
公共GetXMLTask(活动上下文){
this.context=上下文;
}
受保护的void onPostExecute(列出视频){
listViewAdapter=新的CustomListViewAdapter(上下文、视频);
setAdapter(listViewAdapter);
}
/*
*使用HttpURLConnection从Android发出Http下载请求
*XML文件
*/
私有字符串getXmlFromUrl(字符串urlString){
StringBuffer输出=新的StringBuffer(“”);
试一试{
InputStream=null;
URL=新URL(URL字符串);
URLConnection=url.openConnection();
HttpURLConnection httpConnection=(HttpURLConnection)连接;
setRequestMethod(“GET”);
httpConnection.connect();
if(httpConnection.getResponseCode()==HttpURLConnection.HTTP\u确定){
stream=httpConnection.getInputStream();
BufferedReader buffer=新的BufferedReader(
新的InputStreamReader(stream));
字符串s=“”;
而((s=buffer.readLine())!=null)
输出。追加;
}
}捕获(例外情况除外){
例如printStackTrace();
}
返回output.toString();
}
@凌驾
受保护列表doInBackground(字符串…URL){
列表视频=空;
字符串xml=null;
for(字符串url:url){
xml=getXmlFromUrl(url);
InputStream=新的ByteArrayInputStream(xml.getBytes());
videos=SAXXMLParser.parse(流);
for(Cmd:videos){
字符串videoName=cmd.getVideoName();
//字符串getVideos=cmd.getVideos();
字符串getVideo=cmd.getVideo();
字符串getVideoURL=cmd.getVideoURL();
一串
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;
    }
}
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;
        }
    }
}
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;
    }

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

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