2012-01-01 81 views
2

我想在Spinner中使用SimpleCursorAdapter。使用ormlite获取与原始sql的游标

我发现如何返回一个光标。

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; 

但微调需要一个_id字段,我只会有一个id字段的对象。我宁愿避免该领域的重命名。

我该如何解决这个问题?我真的需要将ID与所有微调器字段相关联。

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

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

我真的所有的解决方案开放

问候

回答

4

好吧,我刚刚发现这似乎是有效的,简单的,并符合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"); 
8

您可以通过使用QueryBuilder,而无需求助于原始查询从ORMLite得到根本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(); 
} 
+3

当我使用此代码为'SimpleCursorAdapter'我得到一个'StaleDataException '因为调用'iterator.closeQuietly()'。现在我只是评论了这一点,但恐怕会造成内存泄漏。 – theblang 2014-04-13 05:29:49