Convert results of SQLite Cursor to my object
Asked Answered
F

2

12

I've executed some queries on my SQLite DB on Android.

Main instruction used is this:

Cursor cursor = myDB.rawQuery(select, null);

Now I want the results of this query to be converted to a generic class I've created in the project. If you think I want an ORM system, you are right, but all I've found now are ORM systems that want to query the DB, save objects in the DB and manage the DB itself.

Instead now I need a 'simple' ORM feature that can do exactly what the google.gson library does with JSON strings, it converts JSON strings to custom objects, and I want the same but for converting SQLite cursors to my Classes.

Any suggestion how to do this?

Fever answered 25/1, 2012 at 20:4 Comment(0)
M
17

I don't think there is an automated way to do this. Just populate the object yourself. For example, if your cursor was just an id and a name and you wanted to create a Person object:

Person populatePerson(Cursor cursor)
{
    try
    {
        int idIndex = cursor.getColumnIndexOrThrow("_id");
        int nameIndex = cursor.getColumnIndexOrThrow("name");
        long id = cursor.getLong(idIndex);
        String name = cursor.getString(nameIndex);
        return new Person(id, name);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}

You could wrap this function in your own Cursor class to make the process transparent.

Metalworking answered 25/1, 2012 at 20:21 Comment(1)
The column names are generated dynamically, those are not knowing initially. How can I convert those values to JSON string.? Is any other way for converting the JSON string?False
N
8

Check out MicroOrm

private static class SomeObject {
  @Column(SOME_FIELD)
  private String mSomeField;
}

SomeObject object = microOrm.fromCursor(cursor, SomeObject.class);
New answered 3/7, 2015 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.