如何从无法访问lifeCycleOwner进行观察的资源库中获取LiveData的价值?

问题描述 投票:2回答:4

我已经在我的应用程序中使用了MVVMROOMdatabindig。根据 Guide to app architecture,我想使用空间兑现数据。在xml项目的RecyclerView布局中,我使用[C0 ]变量。我从CategoryViewModel类型的Room数据库中获得类别列表。我想将LiveData类型更改为LiveData<list<CategoryItem>>类型。因为最后我的适配器使用了MutableLiveData<ArrayList<CategoryViewModel>>数据类型。如何获取ArrayList<CategoryViewModel>的值?当我调用LiveData方法时,返回null。这是getValue()模型:

CategoryItem

这是 @Entity(tableName = "category_table") public class CategoryItem implements Serializable { @PrimaryKey private int id; private String title; private String imagePath; @TypeConverters({SubCategoryConverter.class}) private ArrayList<String> subCategory; @TypeConverters({DateConverter.class}) private Date lastRefresh; public CategoryItem(int id, String title, String imagePath, ArrayList<String> subCategory, Date lastRefresh) { this.id = id; this.title = title; this.imagePath = imagePath; this.subCategory = subCategory; this.lastRefresh=lastRefresh; } public CategoryItem(int id, String title, String imagePath) { this.id = id; this.title = title; this.imagePath = imagePath; } public CategoryItem() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public ArrayList<String> getSubCategory() { return subCategory; } public void setSubCategory(ArrayList<String> subCategory) { this.subCategory = subCategory; } public Date getLastRefresh() { return lastRefresh; } public void setLastRefresh(Date lastRefresh) { this.lastRefresh = lastRefresh; } } 类:

CategoryViewModel

这是 public class CategoryViewModel extends AndroidViewModel { private String title; private String imagePath; private MutableLiveData<ArrayList<CategoryViewModel>> allCategories=new MutableLiveData<>(); private CategoryRepository repository; public CategoryViewModel(@NonNull Application application) { super(application); repository=new CategoryRepository(application, Executors.newSingleThreadExecutor()); } public void init(CategoryItem categoryItem){ this.title=categoryItem.getTitle(); this.imagePath=categoryItem.getImagePath(); } public MutableLiveData<ArrayList<CategoryViewModel>> getAllCategories(){ allCategories=repository.getCategory(); return allCategories; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImagePath() { return imagePath; } } 类:

CategoryRepository

这是 public class CategoryRepository { private static final String TAG="CategoryRepository"; private static int FRESH_TIMEOUT_IN_MINUTES = 1; private final Executor executor; private APIInterface apiInterface; public MutableLiveData<ArrayList<CategoryViewModel>> arrayListMutableLiveData=new MutableLiveData<>(); private CategoryDao categoryDao; private Application application; public CategoryRepository(Application application,Executor executor) { this.executor = executor; this.application = application; apiInterface= APIClient.getClient().create(APIInterface.class); LearnDatabase database= LearnDatabase.getInstance(application); categoryDao=database.categoryDao(); } public MutableLiveData<ArrayList<CategoryViewModel>> getCategory(){ refreshCategory(); List<CategoryItem> items; categoryDao.loadCategoryItem(); items=categoryDao.loadCategoryItem().getValue(); // return null CategoryItem category; ArrayList<CategoryViewModel> arrayList=new ArrayList<>(); for(int i=0;i<items.size();i++){ category=items.get(i); CategoryViewModel categoryViewModel=new CategoryViewModel(application); categoryViewModel.init(category); arrayList.add(categoryViewModel); } arrayListMutableLiveData.setValue(arrayList); return arrayListMutableLiveData; } private void refreshCategory(){ executor.execute(() -> { String lastRefresh=getMaxRefreshTime(new Date()).toString(); boolean sliderExists =(!(categoryDao.hasCategory(lastRefresh)).isEmpty()); Log.e(TAG,"sliderExist: "+sliderExists); Log.e(TAG,"lastrefresh: "+lastRefresh); Log.e(TAG,"hasSlider: "+categoryDao.hasCategory(lastRefresh).toString()); // If user have to be updated if (!sliderExists) { Log.e(TAG,"in if"); apiInterface.getCategory().enqueue(new Callback<List<CategoryItem>>() { @Override public void onResponse(Call<List<CategoryItem>> call, Response<List<CategoryItem>> response) { executor.execute(() -> { List<CategoryItem> categories=response.body(); for (int i=0;i<categories.size();i++){ categories.get(i).setLastRefresh(new Date()); categoryDao.saveCategory(categories.get(i)); } }); } @Override public void onFailure(Call<List<CategoryItem>> call, Throwable t) { Log.e(TAG,"onFailure "+t.toString()); } }); } }); } private Date getMaxRefreshTime(Date currentDate){ Calendar cal = Calendar.getInstance(); cal.setTime(currentDate); cal.add(Calendar.MINUTE, -FRESH_TIMEOUT_IN_MINUTES); return cal.getTime(); } } 的项目的xml布局:

recyclerView

这是 <?xml version="1.0" encoding="utf-8"?> <layout> <data class="CategoryDataBinding"> <variable name="category" type="com.struct.red.alltolearn.viewmodel.CategoryViewModel"/> </data> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="200dp" android:layout_height="150dp" app:cardCornerRadius="15dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imgItemCategory" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" app:imageUrl="@{category.imagePath}" /> <TextView android:id="@+id/txtTitleItemCategory" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="@{category.title}" android:textColor="#FFFFFF" android:textSize="20sp" android:textStyle="bold" /> </RelativeLayout> </android.support.v7.widget.CardView> </layout> 类:

CategoryDao

公共接口CategoryDao {

@Dao

}

最后我在片段中观察到@Query("SELECT * FROM course_table") LiveData<List<CategoryItem>> loadCategoryItem(); @Insert(onConflict = OnConflictStrategy.REPLACE) void saveCategory(CategoryItem category); @Query("SELECT * FROM category_table WHERE lastRefresh > Date(:lastRefreshMax)") List<CategoryItem> hasCategory(String lastRefreshMax);

MutableLiveData
android mvvm android-room android-viewmodel android-livedata
4个回答
6
投票

您的问题在这里,对吧?


3
投票

您正在尝试从错误的表categoryViewModel = ViewModelProviders.of(this).get(CategoryViewModel.class); categoryViewModel.getAllCategories().observe(this, new Observer<List<CategoryItem >>() { @Override public void onChanged(@Nullable List<CategoryItem > categoryItems) { categoryAdapter = new CategoryAdapter(getContext(), categoryItems); ... 中加载数据


1
投票

也许您可以使用转换信息?


0
投票

您的https://developer.android.com/topic/libraries/architecture/livedata#transform_livedata将没有任何值,除非您对其调用observe。

© www.soinside.com 2019 - 2024. All rights reserved.