Firebase 无法填充ArrayList类型的MutableLiveData,结果始终为null

Firebase 无法填充ArrayList类型的MutableLiveData,结果始终为null,firebase,android-studio,kotlin,android-livedata,Firebase,Android Studio,Kotlin,Android Livedata,我正在处理一个quizgame,我想在一个可变LiveData arraylist中存储一些ID。因此,我做了一个函数来循环de数据库中的所有文档,并将每个ID添加到arraylist中。但结果总是无效的。我不知道我哪里出错了 我正在使用MVVM结构 GameViewModel: class GameViewModel : ViewModel() { // database instance val db = FirebaseFirestore.getInstance() // the cu

我正在处理一个quizgame,我想在一个可变LiveData arraylist中存储一些ID。因此,我做了一个函数来循环de数据库中的所有文档,并将每个ID添加到arraylist中。但结果总是无效的。我不知道我哪里出错了

我正在使用MVVM结构

GameViewModel:

class GameViewModel : ViewModel() {

// database instance
val db = FirebaseFirestore.getInstance()

// the current category
private val _category = MutableLiveData<String>()
val category: LiveData<String>
    get() = _category

// the list of questionIds of the selected category
private val _questionIdsArray = MutableLiveData<ArrayList<Long>>()
val questionIdsArray: LiveData<ArrayList<Long>>
    get() = _questionIdsArray

// the current question
private val _question = MutableLiveData<String>()
val question: LiveData<String>
    get() = _question


/**
 * Set Current Category
 */
fun SetCategory (categoryName: String){
    _category.value = categoryName
}

/**
 * Get the list of QuestionIds
 */
fun GetListQuestionIds() {
    db.collection("questions")
        .whereEqualTo("category", "$_category")
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                _questionIdsArray.value?.add(document.data["questionid"] as Long)
                Log.d("GetSize","${_questionIdsArray.value?.size}")
            }
            Log.d("GetSize2","${_questionIdsArray.value?.size}")
        }
        .addOnFailureListener { exception ->
            Log.w("errorforloop", "Error getting documents: ", exception)
        }
}
/**
 * Get a Question
 */
fun GetQuizQuestion() {
    Log.d("retro","${_questionIdsArray.value?.size}")
    db.collection("questions")
        .whereEqualTo("category", "$_category")
        .whereEqualTo("questionid", "${_questionIdsArray.value?.get(0)}")
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {
                _question.value = document.data["question"].toString()
            }
        }
        .addOnFailureListener { exception ->
            Log.w("err", "Error getting documents: ", exception)
        }
}

如果有人能启发我…

你的问题

您没有初始化数组。这是您的代码:

// the list of questionIds of the selected category
private val _questionIdsArray = MutableLiveData<ArrayList<Long>>()
val questionIdsArray: LiveData<ArrayList<Long>>
    get() = _questionIdsArray
但是当然,
value
从未初始化过,所以它是空的,所以
add
没有操作(不执行任何操作)

解决方案

只需确保在某个时刻初始化实时数据对象

您可以在声明中内联执行此操作:

// the list of questionIds of the selected category
private val _questionIdsArray = MutableLiveData<ArrayList<Long>>(arrayListOf())
val questionIdsArray: LiveData<ArrayList<Long>>
    get() = _questionIdsArray
//所选类别的问号列表
private val\u questionIdsArray=MutableLiveData(arrayListOf())
val questionIdsArray:LiveData
get()=\u数组
或者在尝试填充列表时:

    .addOnSuccessListener { documents ->
        val idsArray = arrayListOf<Long>() // Non-null list to add to
        for (document in documents) {
            idsArray.add(document.data["questionid"] as Long)
            Log.d("GetSize","${idsArray.size}")
        }

        _questionIdsArray.value = idsArray // Now set live data with a valid list
        Log.d("GetSize2","${_questionIdsArray.value?.size}")
    }
.addOnSuccessListener{documents->
val idsArray=arrayListOf()//要添加到的非空列表
for(文档中的文档){
idsArray.add(document.data[“questionid”]长度相同)
Log.d(“GetSize”,“${idsArray.size}”)
}
_QuestionIDSRARY.value=IDSRARY//现在使用有效列表设置实时数据
Log.d(“GetSize2”,“${u QuestionIDSRARY.value?.size}”)
}

谢谢您的回答,但我仍然得到一个indexOutofBounds异常:Index:0,Size:0,我尝试了两种解决方案,但得到的例外是相同的,您正在调用
\u questionIDSRARY.value?.get(0)
这是列表的第一个元素,但您的列表是空的,因此没有第一个元素。你需要检查这种可能性并加以处理
// the list of questionIds of the selected category
private val _questionIdsArray = MutableLiveData<ArrayList<Long>>(arrayListOf())
val questionIdsArray: LiveData<ArrayList<Long>>
    get() = _questionIdsArray
    .addOnSuccessListener { documents ->
        val idsArray = arrayListOf<Long>() // Non-null list to add to
        for (document in documents) {
            idsArray.add(document.data["questionid"] as Long)
            Log.d("GetSize","${idsArray.size}")
        }

        _questionIdsArray.value = idsArray // Now set live data with a valid list
        Log.d("GetSize2","${_questionIdsArray.value?.size}")
    }