【问题标题】:Displaying multiple Items in simple_list_item_1在 simple_list_item_1 中显示多个项目
【发布时间】:2012-03-12 13:40:10
【问题描述】:

我遵循本指南http://www.vogella.de/articles/AndroidSQLite/article.html 并更改了表格和代码以处理其他字段。但是当列表显示时,它只显示项目字段而不是价格。我找不到它在代码中的哪个位置执行此操作。

这是将项目加载到适配器中的代码,getAllItems 返回和项目数组。商品有 id、item 和 price。

    List<Item> values = datasource.getAllItems();

    // Use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);

这是其背后的代码:

        public List<Item> getAllItems() {


            List<Item> items = new ArrayList<Item>();
            Cursor cursor = database.query(MySQLiteHelper.TABLE_ITEMS,
                    null, null, null, null, null, null);
            cursor.moveToFirst();

            while (!cursor.isAfterLast()) {
                Item item = cursorToItem(cursor);
                items.add(item);
                cursor.moveToNext();
            }
            // Make sure to close the cursor
            cursor.close();
            return items;
        }

        private Item cursorToItem(Cursor cursor) {
            Item item = new Item();
            item.setId(cursor.getLong(0));
            item.setItem(cursor.getString(1));
            item.setPrice(cursor.getString(2));
            return item;
        }

“值”似乎只是 Item.items 而不是价格和 ID,但我不明白为什么?

【问题讨论】:

  • 您需要创建自己的类来扩展 ArrayAdapter 并重写 getView() 方法以提取两个数据片段并将它们各自放入自己的视图中。

标签: java android


【解决方案1】:

如果没有整个私有项目 cursorToItem 的东西,添加怎么样

     while (!cursor.isAfterLast()) { 
                   items.add(cursor.getLong(0) + " " + cursor.getString(1) + " " + cursor.getString(1));               
  cursor.moveToNext(); 
                }

如果您想连续拥有更多对象,您的任务就大得多。我建议你检查this 链接并实现Pankaj 的代码。我已经使用了一段时间,它就像一个魅力。但是,我花了一段时间才明白。

【讨论】:

    猜你喜欢
    • 2019-03-20
    • 2020-10-06
    • 2013-03-09
    • 1970-01-01
    • 2021-12-05
    • 2021-09-17
    • 2017-06-19
    • 1970-01-01
    • 2020-08-17
    相关资源
    最近更新 更多