【发布时间】:2022-01-25 16:50:01
【问题描述】:
我正在尝试从 Firebase 获取数据并将其作为数组返回。到目前为止,这是可行的,但是数据仍然是我设置的默认数据。
这是代码(我添加了一些 cmets 以阐明它在哪里工作以及 id 在哪里不工作):
fun getRandomQuestion() : ArrayList<ArrayList<String>>{
val random = Random(1234567)
val randQuestionId = random.nextInt(0, 27)
var dataRequestResult : String = "empty"
var requestSide1 : String = "empty"
var requestSide2 : String = "empty"
var requestCount1 : String = "empty"
var requestCount2 : String = "empty"
//Get a random question from the DB
Firebase.database.reference.child(Constants.wyrDBQuestionLocation)
.child(randQuestionId.toString())
.get()
.addOnFailureListener { task ->
Log.i("Get WYR Question Status", "Failed: " + task.message.toString())
requestSide1 = "empty"
requestSide2 = "empty"
requestCount1 = "empty"
requestCount2 = "empty"
}.addOnSuccessListener {
Log.i("Get WYR Question Status", "Success")
//Logging this data returns the correct information from firebase, no issue here
Log.i("Request Data Result", it.value.toString())
dataRequestResult = it.value.toString()
}
requestSide1 = dataRequestResult.substringAfter("side1Question=").substringBefore("}")
requestSide2 = dataRequestResult.substringAfter("side2Question=").substringBefore(",")
requestCount1 = dataRequestResult.substringAfter("sideCount1=").substringBefore(",")
requestCount2 = dataRequestResult.substringAfter("sideCount2=").substringBefore(",")
//Return the value
return arrayListOf(arrayListOf(requestSide1, requestCount1), arrayListOf(requestSide2, requestCount2))
}
我尝试获取返回值的活动:
val myQuestion = databaseController.getRandomQuestion()
//This is where the issue lies
//When I get the returned data from the function above, it gives me all of the defaults I had set in the function (which is "empty")
//It logs:`[["empty", "empty"],["empty", "empty"]]`
Log.i("My Question", myQuestion.toString())
成功监听中的数据是正确的,但是返回值还是默认的。 这是日志的图像:
“请求日志结果”,不介意结果,我在做一个WYR应用。
我注意到来自侦听器的请求是最后一个,而不是第一个
我认为这与尚未完全收集的数据有关,因为在我制作的另一个应用程序中,我所要做的就是给它一个延迟并且它会被设置,但在这种情况下,我不知道怎么办。
任何帮助将不胜感激! :)
【问题讨论】:
-
这能回答你的问题吗? Why does my function that calls an API return an empty or null value?。这些调用是异步的,这意味着侦听器代码将运行得更晚(服务器调用很慢)。使用硬编码延迟是一个非常糟糕的主意,您需要组织代码来处理缓慢或快速的服务器响应。见this example
-
我认为您很可能有兴趣阅读以下文章,How to read data from Firebase Realtime Database using get()?。
标签: android firebase kotlin firebase-realtime-database kotlin-coroutines