我有一个Lure
类,其中包含ArrayList
类的LureImage
,如下面的代码所示。在我的存储库中,我进行数据库调用以获取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;
}
}
答案 0 :(得分:0)
Get images in adapter.
class YourAdapter() : RecyclerView.Adapter<Recyclerview.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// place your asynctask here
}
}
Hope this helps. Let me know