【问题标题】:Run a function in its entirety before moving to next activity在移动到下一个活动之前完整地运行一个函数
【发布时间】:2019-08-23 02:35:22
【问题描述】:

我想单击一个按钮,该按钮将从 Firebase 中提取一些数据,然后我想转到下一个活动,传递一个包含 Firebase 数据的数组。我仍然无法理解异步代码,我希望有人能用最简单的方法帮助我完成这个任务。

我已经尝试过运行阻塞、挂起功能、等待和异步,但我似乎无法做到正确。这是我的点击监听器:

btn_games_quiz.setOnClickListener {

    listenForQuestions()

    val intent = Intent(this, QuizActivity::class.java)
    intent.putExtra("questionArray", questionArray)
    startActivity(intent)

}

这里是listenForQuestions:

private fun listenForQuestions(){

    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("MM")
    val formatted = current.format(formatter)
    val currentMonth = QuizActivity.months[formatted.toInt()]

    val ref = FirebaseDatabase.getInstance().getReference("/quizzes/$currentMonth")

    ref.addChildEventListener(object: ChildEventListener {

        override fun onChildAdded(p0: DataSnapshot, p1: String?) {
                val questionItem = p0.getValue(Question::class.java)

                if (questionItem != null) {
                    questionArray += questionItem
                }
        }

        override fun onCancelled(p0: DatabaseError) {
        }

        override fun onChildChanged(p0: DataSnapshot, p1: String?) {
        }

        override fun onChildMoved(p0: DataSnapshot, p1: String?) {
        }

        override fun onChildRemoved(p0: DataSnapshot) {
        }
    })

}

我们将不胜感激。

【问题讨论】:

    标签: android android-intent kotlin


    【解决方案1】:

    尝试使用线程。 新的可运行();

    【讨论】:

      【解决方案2】:

      我建议在协程中运行它。

      对于使用协程的异步编程,请查看此链接。 https://kotlinlang.org/docs/reference/coroutines-overview.html

      【讨论】:

      • 我知道这可能与协程有关。我被引导到文件,例如您之前链接的文件,但没有成功。无论我似乎在做什么,无论是定义挂起函数、使用 runBlocking 等等,每次当代码到达“onChildAdded”时,它都会继续执行其他操作。我需要做的就是在执行其他任何操作之前执行 onChildAdded,但我似乎做不到。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2012-07-17
      相关资源
      最近更新 更多