Я создал базу данных комнат, используя архитектуру комнат Android. теперь из фрагмента просмотра переработчика, когда пользователь нажимает на один из элементов утилизатора, приложение берет его для подробного описания активности этого элемента.
Теперь я отправляю идентификатор элемента из фрагмента, используя следующий код:
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);
}
, и он работает, потому что идентификатор достигает другой стороны.
Мне нужна помощь для анализа или загрузки этих данных с использованием идентификатора в операцию детализации.
это моя деталь Активность:
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();
}
}