0

Quiz app, categories have questions and questions have answers.

I have two queries in the DAO.

In the first one, I get all the categories from the data:

@Query("SELECT * from category_table ORDER BY category_id")
fun getAllCategories(): LiveData<List<Category>>

In the second one, I get a list of questions and answers by category id:

@Query("SELECT * FROM question_table WHERE parent_category_id = :categoryId ")
fun getQuestionsWithAnswersByCategoryId(categoryId: Long): LiveData<List<QuestionWithAnswers>>

Repository:

val getAllCategories: LiveData<List<Category>> = quizDao.getAllCategories()

fun getQuestionsWithAnswersByCategoryId(id: Long): LiveData<List<QuestionWithAnswers>> {

    return quizDao.getQuestionWithAnswers(id)

}

This is my viewmodel:

val getAllCategories: LiveData<List<Category>>
var questionById: LiveData<List<QuestionWithAnswers>>


 init {
        getAllCategories = repository.getAllCategories

        questionByCategoryId = repository.getQuestionWithAnswersByCategoryId(???????)
    }

The problem is that I don't know the categories' id beforehand and need to obtain them from the database.

when I try to obtain a category id in the viewmodel like this:

var categoryId = getAllCategories.value[0].categoryId

it returns null.

Is there any way to obtain categories id which wrapped in livedata inside a viewmodel?

Tyler
  • 11
  • `catergoryID` is null, because it is not `observerd` and you can't `observer` livedata from your viewmodel. My question is: Do you need the livedata object in your viewmodel or will it be `observed` from a view? – Andrew Sep 22 '20 at 12:40
  • Yes, it will be observed in a view, however I also need the data from it in the viewmodel. – Tyler Sep 22 '20 at 14:21

0 Answers0