【问题标题】:Getting data from SQLite database to String Android从 SQLite 数据库获取数据到 String Android
【发布时间】:2012-05-26 16:49:56
【问题描述】:

我正在尝试从我的数据库中获取信息并将其放入字符串中以在屏幕上打印。我想我可以使用下面的代码来做到这一点,但它给出了一些关于光标的信息,而不是光标内的信息。

datasource = new DataBaseHelper(this);
datasource.open();
Cursor c = datasource.getAllGoals();
startManagingCursor(c);
String g = c.toString();
goal.setText(g);
datasource.close();

【问题讨论】:

  • 如何获取信息?你能更具体一点吗?使用String g = c.toString(),您只能获得stringcursor object 表示形式。对于从游标获取信息,您应该使用getters 和允许您通过数据传递的方法。

标签: android sqlite cursor


【解决方案1】:

游标可以被认为是指向一些底层数据的指针。在游标对象上运行c.toString() 将打印其字符串表示的默认Cursor 类的实现(@ 的符号字符和对象哈希码的无符号十六进制表示),这不是您想要的.

要检索基础数据库数据,您需要调用c.getString(columnIndex) (source),或该特定列索引所需的任何列数据类型。

这是一个例子modified from source

假设你已经创建了一个表

private static final String DATABASE_CREATE = 
            "create table comments ( "
            + "_id integer primary key autoincrement, "
            + "comment text not null);";

您的getAllGoals 函数返回一个光标,该光标指向关于两者 _idcomment 的数据。现在您只想显示有关comment 列的详细信息。所以你必须运行c.getString(1)。假设您的getAllGoals 函数返回一个游标,该游标仅指向有关comment 列的数据。现在你必须运行c.getString(0)

我建议您下载提供的示例中的源代码,并了解如何从游标中检索数据。

编辑:

    public List<Comment> getAllComments() {
        List<Comment> comments = new ArrayList<Comment>();

        Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
                allColumns, null, null, null, null, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {//retrieve data from multiple rows
            Comment comment = cursorToComment(cursor);
            comments.add(comment);
            cursor.moveToNext();
        }
        // Make sure to close the cursor
        cursor.close();
        return comments;
    }

    private Comment cursorToComment(Cursor cursor) {
        Comment comment = new Comment();
        comment.setId(cursor.getLong(0));
        comment.setComment(cursor.getString(1));
        return comment;
    }

source

【讨论】:

  • 列索引指的是什么。我需要改变它还是这正是所需要的>
  • 所以如果我从数据库中得到几位信息,我会为每一位信息运行几次?
  • 如果您的意思是 getAllGoals 返回多条信息,则需要使用 while 循环。再次查看我的答案以获取更新的示例。
  • 请注意,您需要知道 getAllGoals 函数返回的光标所指向的数据类型。这样,您可以在光标上调用适当的 getter 方法。
  • 好的,所以如果它是一个 get int 它的 getInteger(0);我知道了。虽然当我运行 get 字符串时它崩溃了应用程序
【解决方案2】:
openDataBase();
Cursor c = myDataBase.rawQuery("SELECT * FROM tb_aa_City where City_Name = '"+cityname+"'", null);
if (c.getCount() > 0) {
    c.moveToFirst();
    seqid = c.getString(4);
    System.out.println("In DB..getSequenceID..."+seqid);
    }
    c.close();
    myDataBase.close();
    SQLiteDatabase.releaseMemory();

【讨论】:

  • 我如何获得 c.getString(int);指向正确的信息
  • c.getString(Colomn number) // 给数据库列号
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-04-02
  • 2016-05-08
  • 2014-06-30
  • 1970-01-01
  • 2017-02-01
相关资源
最近更新 更多