如何从房间访问中获取游标对象列表?

pcj*_*pcj 9 android android-sqlite android-room

我正在尝试使用我的代码来使用房间数据库API.对于文档表我已经定义了Entity类Document,当我查询getAll()它时返回我的所有文档.

现在我有了适应器的旧实现,它使用户Cursor(它的a CursorAdapter).在我的DocumentDao类中,我定义了一个方法来获取光标对象列表.我的Dao课程如下:

@Dao
public interface DocumentDao {

    @Query("SELECT * FROM documents")
    List<com.myapp.room.entity.Document> getAll();

    @Query("SELECT * FROM documents")
    List<Cursor> getCursorAll();
}
Run Code Online (Sandbox Code Playgroud)

在编译期间,我收到以下错误:

Error:(20, 18) error: Not sure how to convert a Cursor to this method's return type
Run Code Online (Sandbox Code Playgroud)

Room的官方指南指出:

如果您的应用程序逻辑需要直接访问返回行,则可以从查询中返回Cursor对象,如以下代码段所示:

@Dao
public interface MyDao {
    @Query("SELECT * FROM user WHERE age > :minAge LIMIT 5")
    public Cursor loadRawUsersOlderThan(int minAge);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是我是否需要为此目的编写转换器?

Pel*_*cho 12

你要回来List<Cursor>而不是Cursor.更改:

@Query("SELECT * FROM documents")
List<Cursor> getCursorAll();
Run Code Online (Sandbox Code Playgroud)

对于

@Query("SELECT * FROM documents")
Cursor getCursorAll();
Run Code Online (Sandbox Code Playgroud)

  • 就别管了.任何人都可能犯同样的错误;) (2认同)