Search code examples
androidkotlinandroid-roomdaoandroidx

Room DAO keeps returning NULL


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?

enter image description here

enter image description here


Solution

  • Here is what I have done:

    • creating instance of facultyRepository inside AndroidViewModel, like this: private val facultyRepository = FacultyRepository(application)
    • also creating a variable (faculties) to store the result in some mutable livedata, like this: val faculties: MutableLiveData<List<Faculty>> = MutableLiveData(ArrayList())
    • inside a method called 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.