I am working on my first app where I can add, edit, delete,... objects in a SQ Lite database. This all works fine so far. Also loading all stored objects with LiveData works fine.
Can anybody advice me, how the code in the repository should look like, when I want to load a single object from my database?
The code in the Dao looks like that:
@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
Lens getLensById(int lensId);
I tried with a simple code like this in the repository:
public Lens getLensById(int id) {
Lens lens = lensDao.getLensById(id);
}
But that does not work - I assume the problem is that this should be done in an Asynchronous Task as I use it for deleting an item.
public void delete(Lens lens) {
new DeleteLensAsyncTask(lensDao).execute(lens);
}
private static class DeleteLensAsyncTask extends AsyncTask<Lens, Void, Void> {
private final LensDao lensDao;
private DeleteLensAsyncTask(LensDao lensDao) {
this.lensDao = lensDao;
}
@Override
protected Void doInBackground(Lens... lenses) {
lensDao.delete(lenses[0]);
return null;
}
}
And there is where I begin to struggle - how should the methods look like in the repository?
In the activity, respectively in the ViewHolder I am using this code which is called from the onCreate method of the activity.
public Lens getLensById(int id) {
return repository.getLensById(id);
}
Thank you so much!
CodePudding user response:
interface
@Query("SELECT * FROM lens_table WHERE id = :lensId LIMIT 1")
LiveData<Lens> getLensById(int lensId);
repo
public LiveData<Lens> getLensById(int id) {
return lensDao.getLensById(id);
}
ViewModel
public LiveData<Lens> getLensById(int id){
return repo.getLendsById(id)
}
Activity
viewModel.getLensById(id = ).observe(this,new Observer{
@Override
void onChanged(Lens lens){
//TODO()
}
})