在simple_list_item_1中显示多个项目

时间:2012-03-12 13:40:10

标签: java android

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

以下是将项加载到适配器,getAllItems返回和项数组的代码。物品有ID,物品和价格。

    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但是我不明白为什么?

1 个答案:

答案 0 :(得分:0)

没有整个私有Item的cursorToItem东西,如何添加

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

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