简体   繁体   English

Android使用光标填充listview

[英]Android populate listview with cursor

My app uses a simple SQLite database. 我的应用程序使用简单的SQLite数据库。 Everything works fine I can now present a Toast with a chosen row from the return query using: 一切正常我现在可以使用以下命令从返回查询中呈现带有所选行的Toast

{
    //etc etc etc...

    c.movetofirst();
    DisplayTitle(c);
}
public void DisplayTitle(Cursor c)
{
    Toast.makeText(main.this, 
            "id: " + c.getString(0) + "\n" +
            "reg: " + c.getString(1) + "\n" +
            "type: " + c.getString(2) + "\n",
            Toast.LENGTH_LONG).show();        
}

I want to prsent all the data in the cursor to the screen using a view but I am not sure how to go about this. 我想使用视图将光标中的所有数据呈现到屏幕上,但是我不确定如何执行此操作。 Which view should I use? 我应该使用哪个视图? I just wnt a simple looking grid representation which allows me to scroll through each row in the cursor 我只是想看一个简单的网格表示,它允许我滚动光标中的每一行

Thanks in advance. 提前致谢。

How can I show ALL rows in the Cursor? 如何在Cursor中显示所有行?

There are several ways if you are working with a Cursor , for example see the "moveTo" related methods, here's an example: 如果使用Cursor有几种方法,例如,请参阅“moveTo”相关方法,这是一个示例:

Set<Item> items = new HashSet<Item>(c.getCount());
if (c.moveToFirst()) {
            do {
               Item i = new Item(select(c.getString(0), c.getString(1), c.getString(2));
               set.add(i);
            } while (c.moveToNext());
         }
         if (!c.isClosed()) {
            c.close();
         }

This assumes Item is a data class that has a constructor with three String parameters. 这假设Item是一个具有带三个String参数的构造函数的数据类。 Going with your code, id, reg, and type. 与您的代码,id,reg和类型一起使用。 Usually column 0 will be a numeric ID (not getString, but SQLite uses "manifest typing" so it will sort of dyna-type a String/Long from column 0 -- you may want to AUTOINCREMENT and use getLong there though). 通常,第0列将是一个数字ID(不是getString,但是SQLite使用“清单类型”,因此它会动态地从第0列键入String / Long-您可能要自动输入并在那里使用getLong)。

One you have a collection of items, you can do anything you want with them to display them. 您可以拥有一组项目,您可以对它们进行任何显示的操作。 If you want a scrolling/selectable list, then ListView is an excellent choice. 如果您想要一个滚动/可选择列表,那么ListView是一个很好的选择。 And, you can back it with a CursorAdapter . 并且,您可以使用CursorAdapter来支持它。

Here's an example of a ListView that is populated by a CursorAdapter from an open source project: http://code.google.com/p/and-bookworm/source/browse/trunk/src/com/totsp/bookworm/Main.java (see the inner BookCursorAdapter class, it should get you pointed in the right direction). 这是一个ListView的示例,该示例由CursorAdapter从开放源项目中填充: http : //code.google.com/p/and-bookworm/source/browse/trunk/src/com/totsp/bookworm/Main。 Java (请参阅内部BookCursorAdapter类,它应该使您指向正确的方向)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM