簡體   English   中英

Android Room-關系和LiveData

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM