Q
Q
qqweer2020-10-22 12:46:44
Android
qqweer, 2020-10-22 12:46:44

How can I make it so that when the fragment is closed, it is no longer accessed?

CoroutineScope(Dispatchers.IO).launch {
            while (true) {
                val msg = Message()
                msg.what = mediaPlayer.currentPosition
                handler.sendMessage(msg)
                delay(10)
            }
        }
    }


    @SuppressLint("HandlerLeak")
    var handler = object : Handler(Looper.getMainLooper()) {


        override fun handleMessage(msg: Message) {
            val currentPosition = msg.what

            // Update positionBar
            positionBar.progress = currentPosition

            // Update Labels
            val elapsedTime = createTimeLabel(currentPosition)
            elapsedTimeLabel.text = elapsedTime

            val remainingTime = createTimeLabel(totalTime - currentPosition)
            remainingTimeLabel.text = "-$remainingTime"
        }
    }


It crashes with the text positionBar must not be null, because it is accessed when the fragment is already closed. How to solve it? I thought the point was that I was using Thread, not Coroutines, but it turns out not to be the case. How to decide? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-10-22
@hawkkiller

Omagad.
Read about structured concurrency. Read about the life cycle of fragments.
Everything happens because you mistreat them. Due to the fact that you have changed one tool for another, the mistreatment has not gone away. You must cancel the scope when leaving the fragment (in onDestroyView). And contact the main thread through MainDispatcher, since you are using coroutines.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question