I am getting fragment not attached to context in onResume()

  Kiến thức lập trình

I have one fragment in which onResume() method, I am using requireContext(), but sometimes the application is getting crash when opening that fragment.

Here, is my current code for onResume()

Sometimes what is happening is, my app is launched and I click on namaaz icon on bottom sheet and I got redirected to NamaazDayFragment, now when I came back to my home screen I spend some time on home screen or I put the app in background, so now when I open the app from background or visit the NamaazDayFragment after sometime, application is crashing.

On firebase I am getting log that fragment not attached to context
for below lines
LocationHelper.getUpdatedLocation(requireContext(), namaazViewModel, viewLifecycleOwner) {
val location = SharedPrefHelper.getUserLocation(requireContext()) as UserLocation?

For this 2 lines, I am getting crash.

 override fun onResume() {
        super.onResume()
        requireActivity().runOnUiThread(Runnable {
            adapter.closeView()
        })

        checkIfFragmentAttached {
            LocationHelper.getUpdatedLocation(requireContext(), namaazViewModel, viewLifecycleOwner) {
                val location = SharedPrefHelper.getUserLocation(requireContext()) as UserLocation?
                Handler(Looper.getMainLooper()).postDelayed({
                    if (location != null && customUserLocation == null) {
                        namaazViewModel.getLocationAddressOnlyCity(location)
                            .observe(viewLifecycleOwner, addressObserver)

                        userLocation =
                            SharedPrefHelper.getUserLocation(requireContext())
                        viewModel.getLocationAddress(userLocation)
                            .observe(viewLifecycleOwner, addressObserver)
                        val monthFragment =
                            requireActivity().supportFragmentManager.fragments.find { it is NamaazMonthFragment } as? NamaazMonthFragment
                        monthFragment?.updateData()

                        viewLifecycleOwner.lifecycleScope.launch {
                            requireActivity().runOnUiThread {
                                setNamaazDetailList(userLocation, currentDate)
                                horizontalCalendarViewSetUp()
                                setLatestNamaazPosition(currentDate)
                                mBinding?.tvNotificationSetting?.visibility = View.VISIBLE
                                adapter.updateList(namaazDetailList)
                            }
                        }

                    }
                }, 500)

            }
        }

    }

    private fun checkIfFragmentAttached(operation: (Context) -> Unit) {
        if (isAdded && context != null) {
            context?.let { operation(it) }
        }
    }
object LocationHelper {

    fun getUpdatedLocation(
        context: Context,
        namaazViewModel: NamaazViewModel,
        lifecycleOwner: LifecycleOwner,
        onLocationUpdated: () -> Unit
    ) {

        val fusedLocationProviderClient =
            LocationServices.getFusedLocationProviderClient(context)

        val locationRequest = LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
        if (ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                context, Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {

        }


        fusedLocationProviderClient.requestLocationUpdates(
            locationRequest,
            object : LocationCallback() {
                override fun onLocationResult(locationResult: LocationResult) {
                    super.onLocationResult(locationResult)
                    for (l in locationResult.locations) {
                        val locationForAddress = UserLocation()
                        locationForAddress.latitude = l.latitude
                        locationForAddress.longitude = l.longitude

                        namaazViewModel.getLocationAddressOnlyCity(
                            locationForAddress
                        ).observe(lifecycleOwner, createAddressObserver(context))

                        onLocationUpdated.invoke()
                    }
                }
            },
            Looper.myLooper()
        )
    }


    fun createAddressObserver(context: Context): Observer<String> {
        return androidx.lifecycle.Observer<String> { newLocation ->
            val userLocation = SharedPrefHelper.getUserLocation(context)
            if(userLocation != null){
                val updatedUserLocation = userLocation.copy(
                    fullAddress = newLocation
                )
                SharedPrefHelper.setUserLocation(context, updatedUserLocation)
            }
        }
    }

}
class NamaazActivity : BaseActivity() {


    private val binding: ActivityNamaazBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_namaaz) as ActivityNamaazBinding
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val asharaMode = SharedPrefHelper.getAsharaModeOn(this)
        if (asharaMode) setTheme(R.style.AsharaMainTheme)
        binding.lifecycleOwner = this
        binding.activity = this

        updateToken()

        AnalyticsHelper.trackScreen(this, AnalyticsHelper.SCREENS.NAMAAZ)

        WorkManager.getInstance(applicationContext)
            // requestId is the WorkRequest id
            .getWorkInfoByIdLiveData(App.request.id)
            .observe(this, { workInfo: WorkInfo? ->
                if (workInfo != null) {
                    var progress = workInfo.outputData.getString("DATA")

                }
            })

        initUI()
    }

    private fun initUI() {
        binding.apply {

            layoutToolbar.apply {
                setSupportActionBar(tbMain)
                supportActionBar?.setDisplayHomeAsUpEnabled(true)

            }

            layoutContent.apply {
                vpNamaaz.adapter = NamaazVPAdapter(this@NamaazActivity)

                TabLayoutMediator(tlNamaaz, vpNamaaz) { tab, position ->
                    when (position) {
                        0 -> tab.text = resources.getString(R.string.day)
                        1 -> {
                            tab.text = resources.getString(R.string.month)
                        }
                    }
                }.attach()
                vpNamaaz.offscreenPageLimit = 2

            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_namaaz_header, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.menu_qibla -> startActivity(Intent(this, QiblaActivity::class.java))
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }

    override fun onResume() {
        super.onResume()
        updateToken()

    }
}
class NamaazVPAdapter(fragment: FragmentActivity) : FragmentStateAdapter(fragment) {

    companion object {
        const val TOTAL_FRAGMENT = 2
        private val namaazDayFragment =
            NamaazDayFragment()
        private val namaazMonthFragment = NamaazMonthFragment()
    }

    override fun getItemCount(): Int {
        return TOTAL_FRAGMENT
    }

    override fun createFragment(position: Int): Fragment {
        return when(position){
            0-> namaazDayFragment
            1-> namaazMonthFragment
            else-> namaazDayFragment
        }

    }

}

New contributor

Varshil Soni is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT