【发布时间】:2018-11-17 21:46:13
【问题描述】:
我在我的应用程序中使用来自 android Jet-pack 的 Room Architecture 组件。我已经实现了 Repository 类,我在其中管理我的数据源,例如服务器和 Room 数据库中的数据。我正在使用实时数据来获取我的数据库中存在的所有对象的列表,并且我在我的活动类中附加了一个观察者。一切正常,除了在调用我的服务器之前的一件事我想检查房间中是否存在数据如果房间中存在数据我不想调用服务器以节省资源但是当我尝试从存储库类中的本地数据库获取数据它总是返回 null 我也尝试将观察者附加到它但没有用。
public LiveData<List<AllbrandsdataClass>> getAllBrands() {
brandsDao.getallbrands().observeForever(new Observer<List<AllbrandsdataClass>>() {
@Override
public void onChanged(@Nullable final List<AllbrandsdataClass> allbrandsdataClasses) {
final List<AllbrandsdataClass> listofbrandsobjectfromdb = allbrandsdataClasses;
if (listofbrandsobjectfromdb == null) {
Log.d(TAG, "Repository getallbrands number of brands in the DB is: 0");
} else {
// perform the logic to check and than fetch from server
}
return brandsDao.getallbrands();
}
}
}
这是我在接口类中的getAllBrands()方法,被注释为DAO
@Query("SELECT * FROM AllbrandsdataClass order by timeStamp desc")
LiveData<List<AllbrandsdataClass>> getallbrands();
我想要的是在从服务器获取数据之前检查本地数据库中的数据的存储库类,但是在使用实时数据时我无法做到这一点,如上所示
【问题讨论】:
-
你好 walter ,你找到正确的方法了吗?
-
是的,我找到了。观看此youtu.be/2rO4r-JOQtA?t=340
-
如果您还需要帮助,请告诉我。
标签: java android android-room android-livedata