0

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!

Zudy
  • 49
  • 7

1 Answers1

0

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()
    }
})
yan sam
  • 387
  • 1
  • 7
  • Thanks! The code works fine for me! Is it common practice to use LiveData also for this kind of query? I am not filling a recycler view etc. with those information... LiveData seemed to be that they are used to observe and immediately show changes. Which is probably not always required. – Zudy Dec 03 '21 at 08:49
  • you can use livedata for this, as it avoids the common problem of doing requests on the main thread, which you shouldn't be doing, but you can also use something like rxjava or coroutines – a_local_nobody Dec 03 '21 at 08:52
  • @Zudy yep. you can use livedata for this kind of query. it is simple for this. you can also use kotlin coroutines , asynctask ,rxjava whatever you want. – yan sam Dec 03 '21 at 09:19