2012-01-01 80 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