19

I am trying to chnage my code to make use of room database APIs. For documents table I have defined Entity class Document, when I query getAll() it returns me all the document.

Now I have old implementation of Adapter which makes user of Cursor ( Its a CursorAdapter ). In my DocumentDao class I defined one method to get list of cursor objects. My Dao class as follows :

@Dao
public interface DocumentDao {

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

    @Query("SELECT * FROM documents")
    List<Cursor> getCursorAll();
}

During compile time I am getting following error :

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

The official guide for Room which states that :

If your app's logic requires direct access to the return rows, you can return a Cursor object from your queries, as shown in the following code snippet:

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

My question is do I need to write converter for this purpose ?

Prashant
  • 4,474
  • 8
  • 34
  • 82
  • Updated documentation link (I can't edit the post due to the edit queue being full): https://developer.android.com/training/data-storage/room/accessing-data#query-cursor – big_m Nov 14 '22 at 19:45

1 Answers1

27

You're returning a List<Cursor> instead of a Cursor. Change:

@Query("SELECT * FROM documents")
List<Cursor> getCursorAll();

for

@Query("SELECT * FROM documents")
Cursor getCursorAll();
Alberto S.
  • 7,409
  • 6
  • 27
  • 46
  • Well I completely forgot Cursor itself has multiple object, I just need to iterate over them using cursor.moveToNext() :) I think I should delete my question ? – Prashant Jul 26 '17 at 12:12
  • 8
    Just leave it. Anyone may make the same mistake ;) – Alberto S. Jul 26 '17 at 12:24
  • now how to convert the Cursor's current record into a model object? I looked inside the _Impl.java, and the code is customized and not reusable – Phlip Oct 15 '22 at 03:41