0

Here's the scenario:

1) The starts off with FragmentA, which contains a Google Maps fragment, the camera is moved to the GPS location of the user

2) The user switches to FragmentB, in it there is a Place Autocomplete Fragment where i grab the location the user inputted

3) After clicking a button in FragmentB, it switches back to Fragment A and should move the camera location to the address the user inputted from FragmentB

Problem:

  • i'm getting a lateinit property mMap has not been initialized error when trying to change FragmentA's camera location from FragmentB. But i thought that since FragmentA was already loaded, mMap would still already be initialized. when i switch between my fragments (button nav bar) it keeps the fragment's state, so i know it's not being destroyed.

FragmentB

val button = view.findViewById(R.id.button_register) as Button
        button.setOnClickListener{
            Log.d(TAG, "Clicked")
            val dialog = SuccessDialog()
            dialog.show(fragmentManager, "success dialog")

            mFragmentNavigation.clearStack()
            bottomBar.selectedItemId = R.id.nav_map
            mFragmentNavigation.switchTab(0)
            FragmentA().mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(searchedLocation, 12f))

FragmentA

class FragmentA: BaseFragment(), OnMapReadyCallback, GoogleMap.OnMarkerClickListener {
    lateinit var mMap: GoogleMap

.
.
.

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap
    checkPermission()
    try {
        val success = googleMap.setMapStyle(
            MapStyleOptions.loadRawResourceStyle(
                activity, R.raw.style_json
            )
        )

        if (!success) {
            Log.e(TAG, "Style parsing failed.")
        }
    } catch (e: Resources.NotFoundException) {
        Log.e(TAG, "Can't find style. Error: ", e)
    }

    // location stuff
    mMap.uiSettings.isZoomControlsEnabled = true
    mMap.setOnMarkerClickListener(this)
    mMap.uiSettings.isMapToolbarEnabled = false
}
Barcode
  • 930
  • 1
  • 13
  • 31
  • Sounds like when you are switching from `Fragment A` to `Fragment B`, `Fragment A` is detaching which is causing it to recreate itself when switching back to `Fragment A`. Try saving the view that is inflated when switching between fragments so that you can restore the inflated view when necessary. – remedy. Mar 01 '19 at 00:34
  • @remedy. it's not recreating because in the begining on `FragmentA` i move the map around, then go to B, and switch back to A, and the map position is still the same as i left it. – Barcode Mar 01 '19 at 00:40
  • @remedy. if put `lateinit var mMap: GoogleMap` outside of the class, making it global... then it works.... but i don't think that's a good idea to have to global – Barcode Mar 01 '19 at 00:45

0 Answers0