【问题标题】:Get a cursor with a raw sql with ormlite使用 ormlite 获取带有原始 sql 的游标
【发布时间】:2012-01-31 11:01:29
【问题描述】:

我想将 SimpleCursorAdapter 与 Spinner 一起使用。

我找到了如何返回光标。

QueryBuilder<ChoixPointVerification, Integer> qb = choixPointVerificationDao.queryBuilder();
qb.where().eq(FIELD, id);
PreparedQuery<ChoixPointVerification> preparedQuery = qb.prepare();
AndroidCompiledStatement compiledStatement =
                (AndroidCompiledStatement)preparedQuery.compile(db, StatementType.SELECT);

Cursor cursor = compiledStatement.getCursor();
return cursor;

但是 Spinner 需要一个 _id 字段,而我只有一个带有 id 字段的对象。我宁愿避免重命名该字段。

我该如何解决这种情况?我真的需要将一个 id 关联到所有微调器字段。

我想我也许可以从 rawsql 发出游标,但我不知道如何使用 ormlite。如果我可以使用原始 sql 创建 PreparedQuery 似乎是可能的。

我还读到,如果我有一个 AndroidDatabase 对象,我可以发出一个 Cursor 对象,但是我们如何使用 ormlite 创建一个 AndroidDatabase ?

我对所有解决方案都很开放

问候

【问题讨论】:

    标签: android ormlite


    【解决方案1】:

    我刚刚找到了一个看起来高效、简单且符合 ormlite 的解决方案。

    我只需要得到一个AndroidDatabasegetHelper().getReadableDatabase()

    然后使用

    Cursor cursor = db.query("choixpointverification",
        new String[] { "id", "id as _id", "nom" },
        "masque = 0 and idPointVerification = " + idPointVerification.toString(),
        null, null, null, "tri");
    

    【讨论】:

      【解决方案2】:

      您可以使用QueryBuilderORMLite 获取底层Cursor 对象,而无需求助于原始查询。看看这个答案:

      Android Cursor with ORMLite to use in CursorAdapter

      您可以执行以下代码:

      // build your query
      QueryBuilder<Foo, String> qb = fooDao.queryBuilder();
      qb.where()...;
      // when you are done, prepare your query and build an iterator
      CloseableIterator<Foo> iterator = dao.iterator(qb.prepare());
      try {
         // get the raw results which can be cast under Android
         AndroidDatabaseResults results =
             (AndroidDatabaseResults)iterator.getRawResults();
         Cursor cursor = results.getRawCursor();
         ...
      } finally {
         iterator.closeQuietly();
      }
      

      【讨论】:

      • 当我将此代码用于SimpleCursorAdapter 时,由于调用iterator.closeQuietly(),我得到了StaleDataException。现在我只是把那行注释掉了,但我担心这会造成内存泄漏。
      猜你喜欢
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2023-03-10
      • 2013-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多