In room
, I have a dao to something like this:
@Dao
interface FacultyDao {
@Query("select * from faculty")
fun getAll(): LiveData<List<Faculty>>
...
}
And inside the repository, I'm simply calling this method and logging it:
class FacultyRepository(application: Application) {
private val facultyDao: FacultyDao
init {
val db: AppDB = AppDB.getInstance(application)
facultyDao = db.facultyDao()
}
fun getAllFaculty(): LiveData<List<Faculty>> {
val v = facultyDao.getAll()
Log.d("muaxx", v.value.toString())
return v
}
...
}
But the thing is it's returning me null
, but when I ran that query in inspector it worked. Am I missing something?
Here is what I have done:
facultyRepository
inside AndroidViewModel
, like this: private val facultyRepository = FacultyRepository(application)
faculties
) to store the result in some mutable livedata, like this: val faculties: MutableLiveData<List<Faculty>> = MutableLiveData(ArrayList())
init
I'm observing the getAllFaculty
using observeForever
And yes, I need to call this init
method once, from the fragment.
Relevant code:
class FacultyListViewModel(application: Application) : AndroidViewModel(application) {
private val facultyRepository = FacultyRepository(application)
val faculties: MutableLiveData<List<Faculty>> = MutableLiveData(ArrayList())
fun init() {
facultyRepository.getAllFaculty().observeForever {
faculties.postValue(it)
}
}
}
If you have got some better approach, feel free to suggest here.