【问题标题】:how to load data into a detail activity using row ID?如何使用行 ID 将数据加载到详细活动中?
【发布时间】:2019-10-07 12:16:14
【问题描述】:

我已经使用 android 房间架构构建了一个房间数据库。现在从 recyclerview 片段中,当用户单击其中一个回收器项目时,应用程序会将他带到该项目的详细活动。

现在我使用以下代码从片段中发送项目 ID:

holder.parentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(mContext.getContext(), MaterialItemView.class);
                intent.putExtra("ID", String.valueOf(mMaterial.get(position).getId()));
                mContext.startActivity(intent);
            }

它正在工作,因为 ID 到达了另一端。

我需要帮助来使用 ID 解析或加载此数据到详细信息活动中。

这是我的详细活动:

  TextView mMaterialName;
    TextView mMaterialBrand;
    private RawMaterialViewModel mMaterialViewModel;
    private List<RawMaterialsEntity> mMaterial; // Cached copy of Materials
    RawMaterialsEntity rawMaterialsEntity;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.material_item_view);

        mMaterialName = findViewById(R.id.material_name_view);
        mMaterialBrand = findViewById(R.id.material_brand_view);

        mMaterialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
        // Update the cached copy of the words in the adapter.

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("ID")) {
            int id = intent.getIntExtra("ID", -1);
            // TODO: get material details based on material id


        } else {
            // ...
        }

这是我的道:

@Dao
public interface RawMaterialsDao {

    @Insert
    void insertMaterial(RawMaterialsEntity rawMaterialsEntity);

    @Query("DELETE FROM raw_materials")
    void deleteAll();

    @Query("SELECT * FROM raw_materials WHERE material_name = :name")
    List<RawMaterialsEntity> findMaterial(String name);

    @Query("SELECT * FROM raw_materials WHERE id = :id")
    List<RawMaterialsEntity> findMaterialById(int id);

    @Query("DELETE FROM raw_materials WHERE material_name = :name")
    void deleteMaterial(String name);

    @Query("SELECT * from raw_materials")
    LiveData<List<RawMaterialsEntity>> getAllMaterials();

    @Query ("UPDATE raw_materials SET cost_per_gm = material_cost/material_weight")
    void divide();

    @Query ("UPDATE raw_materials SET total_cost = material_cost*material_quantity")
    void totalCost();

}

我的仓库:

public class ChefsBoxRepository {

    private MutableLiveData<List<RawMaterialsEntity>> searchResults = new MutableLiveData<>();
    private LiveData<List<RawMaterialsEntity>> allMaterials;
    private RawMaterialsDao rawMaterialDao;

    //public constructor
    public ChefsBoxRepository(Application application) {
        ChefsBoxRoomDataBase db;
        db = ChefsBoxRoomDataBase.getDatabase(application);
        rawMaterialDao = db.rawMaterialDao();
        allMaterials = rawMaterialDao.getAllMaterials();

    }

    //used by the view model
    public LiveData<List<RawMaterialsEntity>> getAllMaterials() {
        return allMaterials;
    }
    //used by the view model
    public MutableLiveData<List<RawMaterialsEntity>> getSearchResults() {
        return searchResults;
    }

    public void insertMaterial(RawMaterialsEntity newMaterial) {
        InsertAsyncTask task = new InsertAsyncTask(rawMaterialDao);
        task.execute(newMaterial);
    }

    public void costPerGm(){
        CostPerGmAsyncTask task = new CostPerGmAsyncTask(rawMaterialDao);
        task.execute();
    }

    public void totalCost(){
        TotalCostAsyncTask task = new TotalCostAsyncTask(rawMaterialDao);
        task.execute();
    }
    public void deleteMaterial(String name) {
        DeleteAsyncTask task = new DeleteAsyncTask(rawMaterialDao);
        task.execute(name);
    }

    public void findMaterial(String name) {
        QueryAsyncTask task = new QueryAsyncTask(rawMaterialDao);
        task.delegate = this;
        task.execute(name);
    }

    public void findMaterialById(int id) {
        QueryAsyncTask2 task = new QueryAsyncTask2(rawMaterialDao);
        task.delegate = this;
        task.execute(id);
    }

    private void asyncFinished(List<RawMaterialsEntity> results) {
        searchResults.setValue(results);
    }

    //QueryAsyncTask for calling items from database
    private static class QueryAsyncTask extends
            AsyncTask<String, Void, List<RawMaterialsEntity>> {

        private RawMaterialsDao asyncTaskDao;
        private ChefsBoxRepository delegate = null;

        QueryAsyncTask(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected List<RawMaterialsEntity> doInBackground(final String... params) {
            return asyncTaskDao.findMaterial(params[0]);
        }

        @Override
        protected void onPostExecute(List<RawMaterialsEntity> result) {
            delegate.asyncFinished(result);
        }
    }

    //QueryAsyncTask for calling items from database
    private static class QueryAsyncTask2 extends
            AsyncTask<Integer, Void, List<RawMaterialsEntity>> {

        private RawMaterialsDao asyncTaskDao;
        private ChefsBoxRepository delegate = null;

        QueryAsyncTask2(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected List<RawMaterialsEntity> doInBackground(final Integer... params) {
            return asyncTaskDao.findMaterialById(params[0]);
        }

        @Override
        protected void onPostExecute(List<RawMaterialsEntity> result) {
            delegate.asyncFinished(result);
        }
    }

    //InsertAsyncTask for inserting items to the database
    private static class InsertAsyncTask extends AsyncTask<RawMaterialsEntity, Void, Void> {

        private RawMaterialsDao asyncTaskDao;

        InsertAsyncTask(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(final RawMaterialsEntity... params) {
            asyncTaskDao.insertMaterial(params[0]);
            return null;
        }
    }

    //DeleteAsyncTask for deleting items from the database
    private static class DeleteAsyncTask extends AsyncTask<String, Void, Void> {

        private RawMaterialsDao asyncTaskDao;

        DeleteAsyncTask(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(final String... params) {
            asyncTaskDao.deleteMaterial(params[0]);
            return null;
        }
    }

    //CostPerGmAsyncTask for dividing the  materialCost on the materialWeight
     private static class CostPerGmAsyncTask extends AsyncTask<Void, Void, Void> {

        private RawMaterialsDao asyncTaskDao;

        CostPerGmAsyncTask(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            asyncTaskDao.divide();
            return null;
        }
    }

    //TotalCostAsyncTask for dividing the  materialCost on the materialWeight
    private static class TotalCostAsyncTask extends AsyncTask<Void, Void, Void> {

        private RawMaterialsDao asyncTaskDao;

        TotalCostAsyncTask(RawMaterialsDao dao) {
            asyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            asyncTaskDao.totalCost();
            return null;
        }
    }

}

和我的视图模型:


public class RawMaterialViewModel extends AndroidViewModel {

    private ChefsBoxRepository repository;
    private LiveData<List<RawMaterialsEntity>> allMaterials;
    private MutableLiveData<List<RawMaterialsEntity>> searchResults;
    private List<RawMaterialsEntity> oneRawMaterial;


    public RawMaterialViewModel (Application application) {
        super(application);
        repository = new ChefsBoxRepository(application);
        allMaterials = repository.getAllMaterials();
        searchResults = repository.getSearchResults();

    }

    public MutableLiveData<List<RawMaterialsEntity>> getSearchResults() {
        return searchResults;
    }

    public LiveData<List<RawMaterialsEntity>> getAllMaterials() {
        return allMaterials;
    }

    public void insertMaterial(RawMaterialsEntity material) {
        repository.insertMaterial(material);
    }

    public void findMaterial(String name) {
        repository.findMaterial(name);
    }
    public void findMaterialById(int id) {
        repository.findMaterialById(id);
    }
    public void deleteMaterial(String name) {
        repository.deleteMaterial(name);
    }

    public void costPerGm(){
        repository.costPerGm();
    }

    public void totalCost(){
        repository.totalCost();
    }
}

【问题讨论】:

    标签: android database repository android-room dao


    【解决方案1】:

    我找到了解决方案,为此我需要实现以下内容:

    在道中:

    @Query("SELECT * FROM raw_materials WHERE id = :id")
        LiveData<RawMaterialsEntity> findMaterialById(int id);
    

    在存储库中:

     public LiveData<RawMaterialsEntity> findMaterialById(int id) {
            return rawMaterialDao.findMaterialById(id);
        }
    

    在 ViewModel 中:

        public LiveData<RawMaterialsEntity> findMaterialById(int id) {
            return repository.findMaterialById(id);
        }
    

    最后在详细活动中:

       RawMaterialViewModel materialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
            // Update the cached copy of the words in the adapter.
    
            Intent intent = getIntent();
            if (intent != null && intent.hasExtra("ID")) {
    
                id = intent.getIntExtra("ID", -1);
                // TODO: get material details based on material id
    
                // Set up the materialViewModel
               materialViewModel = new ViewModelProvider(this).get(RawMaterialViewModel.class);
               materialViewModel.findMaterialById(id).observe(this, new Observer<RawMaterialsEntity>() {
                   @Override
                   public void onChanged(RawMaterialsEntity rawMaterialsEntity) {
                       mMaterialName.setText(rawMaterialsEntity.getRawMaterialName());
                       mMaterialBrand.setText(rawMaterialsEntity.getRawMaterialBrand());
                   }
               });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-03
      • 2017-10-25
      • 2022-01-17
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      相关资源
      最近更新 更多