[英]Android Room - Relationships and LiveData
我有一個Lure
類,其中包含LureImage
類的ArrayList
,如下面的代碼所示。 在我的存儲庫中,我進行數據庫調用以獲取LiveData<List<Lure>>
,然后執行AsyncTask
以獲得每個誘餌的List<LureImage>
。 我為此編寫的代碼的問題在於,它並不總是從數據庫中獲取List<LureImage>
,結果是有時RecyclerView顯示圖像,有時卻不顯示圖像。 (我在下面顯示我的意思的屏幕截圖)
public class Lure implements Serializable {
private static final String TAG = "LURE";
@PrimaryKey(autoGenerate = true)
private int id;
private String _lureName;
private String _lureNotes;
@Ignore
private List<LureImage> lureImages = new ArrayList<>();
public Lure() {
}
@Ignore
public Lure(String lureName, String lureNotes) {
this._lureName = lureName;
this._lureNotes = lureNotes;
}
}
從我的LureRepository類中,我設法從數據庫中獲取LiveData>,然后我希望每個Lure從數據庫中獲取其對應的Image類。 我設法用這種方法做到這一點。
public LiveData<List<Lure>> getAllLures() {
LiveData<List<Lure>> luresLiveData = lureDao.getAllLures();
luresLiveData = Transformations.map(luresLiveData, new Function<List<Lure>, List<Lure>>() {
@Override
public List<Lure> apply(List<Lure> input) {
for (final Lure lure : input) {
new GetLureImagesTask(lureDao).execute(lure);
}
return input;
}
});
return luresLiveData;
}
private static class GetLureImagesTask extends AsyncTask<Lure,Void,Void> {
private LureDao lureDao;
public GetLureImagesTask(LureDao lureDao) {
this.lureDao = lureDao;
}
@Override
protected Void doInBackground(Lure... lures) {
lures[0].setLureImages(lureDao.getLureImages(lures[0].getId()));
return null;
}
}
在適配器中獲取圖像。
class YourAdapter() : RecyclerView.Adapter<Recyclerview.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// place your asynctask here
}
}
希望這可以幫助。 讓我知道
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.