【问题标题】:Convert results of SQLite Cursor to my object将 SQLite 游标的结果转换为我的对象
【发布时间】:2012-01-25 20:04:53
【问题描述】:

我在 Android 上的 SQLite DB 上执行了一些查询。

使用的主要指令是这样的:

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

现在我希望将此查询的结果转换为我在项目中创建的通用类。如果你认为我想要一个 ORM 系统,你是对的,但我现在发现的只是 ORM 系统,它们想要查询数据库、将对象保存在数据库中并管理数据库本身。

相反,现在我需要一个“简单”的 ORM 功能,它可以完全完成 google.gson 库对 JSON 字符串所做的工作,它将 JSON 字符串转换为自定义对象,我想要相同的功能,但将 SQLite 游标转换为我的类。

有什么建议吗?

【问题讨论】:

    标签: android gson pojo android-cursor


    【解决方案1】:

    我认为没有一种自动化的方法可以做到这一点。只需自己填充对象。例如,如果您的光标只是一个 id 和一个名称,并且您想创建一个 Person 对象:

    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();
        }
    }
    

    您可以将此函数包装在您自己的 Cursor 类中以使过程透明。

    【讨论】:

    • 列名是动态生成的,最初是不知道的。如何将这些值转换为 JSON 字符串。?有没有其他方法可以转换 JSON 字符串?
    【解决方案2】:

    查看MicroOrm

    private static class SomeObject {
      @Column(SOME_FIELD)
      private String mSomeField;
    }
    
    SomeObject object = microOrm.fromCursor(cursor, SomeObject.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-23
      • 2019-01-24
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2011-09-10
      相关资源
      最近更新 更多