【问题标题】:Android / Java - ListView Populated with XML Data Using ArrayList: Only Displays First ItemAndroid / Java - ListView 使用 ArrayList 填充 XML 数据:仅显示第一项
【发布时间】:2014-02-06 16:58:32
【问题描述】:

我正在尝试通过使用 ArrayList 来使用 XML 数据填充 ListView - 到目前为止我已经能够完成 - 问题是 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>

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

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

}

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

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("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 截图

附:

如果需要任何其他信息 - 请告诉我(我将在接下来的几个小时里在我的办公桌前工作,并且很乐意回答任何问题并及时接受任何答案)

【问题讨论】:

  • 我怀疑它包含在 ListView 或 ViewGroup 中的 layout_width 或 layout_height 中。你可以为你的活动发布你的布局 XML 吗?
  • 另外,您是否考虑过使用 ListActivity 作为 SAXParserAsyncTaskActivity 的父类?
  • 我发布了它(我想我可以/应该 - 但我想在合并之前弄清楚它为什么不起作用!):)
  • 你调试过你的异步任务吗?执行后List&lt;Cmd&gt; videos 中有多少项?
  • videos=ArrayList Array=Object[12]: null, null, null, null, null, null, null, null, null, null, null:(

标签: java android arrays android-listview arraylist


【解决方案1】:

SAXXMLHandler.javaendElement() 方法中,如果qName.equalsIgnoreCase("videos"),您只需将cmd 添加到视频列表中。

在所有其他情况下,您修改了 cmd,但实际上并未将其添加到列表中。您还想在 else if 块中添加 videos.add(cmd) 语句,以便将所有 cmd 添加到列表中。

这里的这个错误是导致您的List&lt;Cmd&gt; videos 只有一项,因此在您的列表视图中只显示一项。

【讨论】:

  • 谢谢先生!非常感谢您的帮助!
  • 关于此的另一个问题... listView 现在已填充 - 但它是一遍又一遍重复的相同数据(而不是 XML 中的每个唯一项目)你知道我可能会做什么吗能够解决这个问题 - 还是我应该开始一个关于这个问题的新线程?
  • 我认为问题再次出在 SAXXMLHandler.java 上。您仅在 startElement() 中创建 new Cmd(我认为这只发生一次,这意味着您每次都重新使用相同的对象)。但正如我之前提到的,我不太了解您的程序流程,所以它可能是别的东西;-)
  • 它基于本教程/示例...(如果有帮助,请告诉我 - 我会看看我能做些什么来修复它,如果没有......你可能会在新帖子中看到呼救声!)再次感谢...theopentutorials.com/tutorials/android/xml/…
  • 我检查了链接,但现在要深入研究的代码太多了 - 应该发布一个新问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-25
  • 1970-01-01
相关资源
最近更新 更多