我有一个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>,然后我想让每个鱼饵从数据库中获取其相应的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;
}
}在这里,我获得了图像并将它们显示在回收器视图中

此处不检索图像

发布于 2018-09-19 16:30:00
获取适配器中的图像。
class YourAdapter() : RecyclerView.Adapter<Recyclerview.ViewHolder>() {
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// place your asynctask here
}
}希望这能有所帮助。让我知道
https://stackoverflow.com/questions/52399908
复制相似问题