如果我们在countdowntimer完成之前更改片段,那么应用程序将在android中崩溃



应用程序一打开,我就使用一个2秒的倒计时计时器。2秒钟后,我看到了线性布局和不可见的进度条。我之所以使用它,是因为我可以通过firebase提取所有数据,并将其分配给相应的文本框。然而,如果我在倒计时期间转到另一个活动,程序就会崩溃。

object : CountDownTimer(1000, 1000) {
override fun onTick(p0: Long) {
}
override fun onFinish() {
linearLayout_profile.visibility = View.VISIBLE
progressBar_profile.visibility = View.INVISIBLE
}
}.start()
2020-12-10 00:50:24.118 1742-1742/com.burakergun.emre E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.burakergun.emre, PID: 1742
java.lang.NullPointerException: linearLayout_profile must not be null
at com.burakergun.emre.Fragment.ProfileFragment$onViewCreated$3.onFinish(ProfileFragment.kt:66)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2020-12-10 00:50:24.185 1742-1742/com.burakergun.emre I/Process: Sending signal. PID: 1742 SIG: 9

我检查了logcat并显示了致命错误。错误表明linearlayout_profile不能为null。linearlayout_profile怎么可能为null。我不明白部分

linearlayout_profile为null,因为您导航到了另一个活动,并且没有对linearlayout_profile的引用,因此为null。

您需要添加null检查以防止崩溃。

当您传递到另一个活动时,您应该销毁计时器

override fun onDestroy() {
super.onDestroy()
timer?.cancel()
}
private var countDownTimer: CountDownTimer? = null
private fun startTimer() {
countDownTimer = object : CountDownTimer(100000, 1000) {
override fun onTick(millisUntilFinished: Long) {
val secondsUntilFinished: Long = ceil(millisUntilFinished.toDouble() / 1000).toLong()
val string: String = getString(R.string.resend_code_after).replace("*", secondsUntilFinished.toString())
binding.resendOTP.text = string
}
override fun onFinish() {
val string: String = getString(R.string.resend_code)
binding.resendOTP.text = string
}
}.start()
}

然后,当你想更改片段或活动时,在onClick或Nav函数中使用此代码,在更改片段或行为之前取消倒计时

countDownTimer!!.cancel()

最新更新