Sobes.tech
Junior — Senior

Bug fixing in View fragment, threads, and working with LocationManager

livecode

Task condition

Find and fix the errors in the following Kotlin code snippet. The program should display the number of presses, change the button text, and after reaching the required count, initiate a request to LocationManager from a separate thread. However, the current implementation violates fragment lifecycle rules and thread handling. Provide a corrected version.

class Frmt(var targetCount: Int) : Fragment() {

    private val contextRef = requireContext()
    private val textView: TextView = requireView().findViewById(R.id.tv)
    private val button: Button = requireView().findViewById(R.id.btn)

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.asdasd, container, true)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        var clicks = 0
        textView.text = "Press $targetCount times to confirm"
        button.text = "Press"
        button.setOnClickListener {
            if (clicks < targetCount) {
                clicks += 1
            } else {
                Thread {
                    (contextRef.getSystemService(Context.LOCATION_SERVICE) as LocationManager)
                        .requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            500,
                            500f
                        ) {
                            val result = executeRequest(
                                it.latitude,
                                it.longitude
                            )

                            Handler(Looper.getMainLooper()).post {
                                if (result) {
                                    textView.text = "Operation successful"
                                } else {
                                    throw Exception("Operation failed, please try again later")
                                }
                            }
                        }
                }.start()
            }
        }
    }
}