2

I'd like to use a SimpleCursorAdapter with a Spinner.

I found how to return a Cursor.

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;

But the Spinner require a _id field and I'll only have an object with an id field. I prefer to avoid the rename of the field.

How can I resolve that case ? I really need to associate an id to all spinner field.

I imagined that I can maybe issue a cursor from a rawsql but I din't find how with ormlite. It seems to be possible if I can create a PreparedQuery with a raw sql.

I also read that if I have an AndroidDatabase object I can issue a Cursor object but how can we create an AndroidDatabase with ormlite ?

I'm really open with all the solution

Regards

P. Sohm
  • 2,842
  • 2
  • 44
  • 77

2 Answers2

8

You can get the underlying Cursor object from ORMLite by using QueryBuilder without having to resort to a raw query. Take a look at this answer:

Android Cursor with ORMLite to use in CursorAdapter

You can do something like the following code:

// 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();
}
Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
  • 3
    When I use this code for a `SimpleCursorAdapter` I get a `StaleDataException` due to the call `iterator.closeQuietly()`. For now I just commented that line out, but I am afraid that will create a memory leak. – theblang Apr 13 '14 at 05:29
4

Well I just found a solution which seems to be efficient, simple, and compliant with ormlite.

I just have to get an AndroidDatabase with getHelper().getReadableDatabase().

and then use

Cursor cursor = db.query("choixpointverification",
    new String[] { "id", "id as _id", "nom" },
    "masque = 0 and idPointVerification = " + idPointVerification.toString(),
    null, null, null, "tri");
Gray
  • 115,027
  • 24
  • 293
  • 354
P. Sohm
  • 2,842
  • 2
  • 44
  • 77