首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android Room -Relationship和LiveData

Android Room -Relationship和LiveData
EN

Stack Overflow用户
提问于 2018-09-19 14:57:54
回答 1查看 161关注 0票数 0

我有一个Lure类,其中包含LureImage类的ArrayList,如下面的代码所示。在我的存储库中,我调用数据库来获取LiveData<List<Lure>>,然后执行AsyncTask来获取每个鱼饵的List<LureImage>。我写的代码的问题是,它并不总是从数据库中获得List<LureImage>,结果是我的RecyclerView有时显示图像,有时不显示。(我展示了下面我所指的屏幕截图)

代码语言:javascript
复制
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类。我设法用这种方法做到了这一点。

代码语言:javascript
复制
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;
 }
    }

在这里,我获得了图像并将它们显示在回收器视图中

此处不检索图像

EN

回答 1

Stack Overflow用户

发布于 2018-09-19 16:30:00

获取适配器中的图像。

代码语言:javascript
复制
    class YourAdapter() : RecyclerView.Adapter<Recyclerview.ViewHolder>() {

          override fun onBindViewHolder(holder: ViewHolder, position: Int) {
                   // place your asynctask here
          }
    }

希望这能有所帮助。让我知道

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52399908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档