【问题标题】:Cannot read content of SQLite DB via Room and LiveData无法通过 Room 和 LiveData 读取 SQLite DB 的内容
【发布时间】:2020-06-17 05:27:09
【问题描述】:

我正在从 SQLite 迁移到 Room 和 LiveData。所以我的 SQLite DB 已经存在于设备上并且里面有一些数据。这是我创建数据库的代码:

public static OfferingsDatabase getInstance(Context context) {
    if(INSTANCE == null) {
        synchronized (LOCK){
            INSTANCE = Room.databaseBuilder(context.getApplicationContext(), OfferingsDatabase.class, "offerings.db")
                    .createFromFile(new File(context.getDatabasePath("offerings.db").getAbsolutePath()))
                    .fallbackToDestructiveMigration()
                    .build();
        }
    }

    return INSTANCE;
}

实例被正确创建。在我使用的 ViewModel 中:

public OfferingsViewModel(Application application) {
    super(application);
    OfferingsDatabase database = OfferingsDatabase.getInstance(application.getApplicationContext());
    offerings = database.offeringsDao().loadAllOfferings();
}

我的道是:

@Dao
public interface OfferingsDao {
    @Query("SELECT * FROM " + OfferingEntity.TABLE_NAME)
    LiveData<List<OfferingEntity>> loadAllOfferings();
}

数据库路径正确,实体定义正确。但是,loadAllOfferings() 会返回一个空列表,尽管有数据。我可以直接执行 SQLite 语句并且效果很好。似乎每次构建数据库时都会擦除数据库。如何实现现有条目显示在 Room 中?

【问题讨论】:

    标签: android sqlite mvvm


    【解决方案1】:

    我想通了。我必须删除 fallbackToDestructiveMigration() 并实施迁移。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多