【问题标题】:GreenDAO: ToMany relation causes SQLite queries to be executed on UI threadGreenDAO:ToMany 关系导致 SQLite 查询在 UI 线程上执行
【发布时间】:2016-08-24 08:32:50
【问题描述】:

在 Entity 上定义 ToMany 关系时,生成的代码如下所示(ProductEntity 与 MediaEntity 具有 ToMany 关系):

/**
 * To-many relationship, resolved on first access (and after reset).
 * Changes to to-many relations are not persisted, make changes to the target entity.
 */
@Generated(hash = 580223476)
public List<MediaEntity> getMedia() {
    if (media == null) {
        final DaoSession daoSession = this.daoSession;
        if (daoSession == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        MediaEntityDao targetDao = daoSession.getMediaEntityDao();
        List<MediaEntity> mediaNew = targetDao._queryProductEntity_Media(productId);
        synchronized (this) {
            if(media == null) {
                media = mediaNew;
            }
        }
    }
    return media;
}

现在,即使我们在后台线程获取ProductEntity的实例(例如使用自定义Loader),它的getMedia()方法也会在UI线程上被调用,这会导致第一次调用getMedia()引起的SQLite查询在 UI 线程上执行。

有没有办法防止这种延迟加载子对象并指示 GreenDao 解决所有依赖关系并在父实体创建/初始化时填充所有字段?

GreenDAO 的 github 页面上对应的支持票链接:https://github.com/greenrobot/greenDAO/issues/416

附:我们可以在从 DaoSession 获取 ProductEntity 之后手动添加对 getMedia() 的调用,但这不是一个有效的解决方案:太容易出错。

【问题讨论】:

    标签: android multithreading android-sqlite greendao


    【解决方案1】:

    正如您所写,通过使用 getter 在后台线程中预加载数据库来避免惰性 getter 与数据库通信。没有更好的办法。

    有时在 UI 线程中调用未初始化的 getter 就可以了。这取决于你的情况。

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2016-07-05
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-01-08
      • 2013-04-08
      • 1970-01-01
      相关资源
      最近更新 更多