Why Fragment SupportMapFragment has not been attached yet

188 views Asked by At

I'm trying to implement supportmapfragment on my fragment but for some reason it gives me error. What I'm doing wrong?

Error I'm getting: java.lang.IllegalStateException: Fragment SupportMapFragment{67446a6} (09078183-572b-41c6-8795-7441157371d5) has not been attached yet.

supportMapFragment.getMapAsync(this). Is never called it crash before that

class MapFragment : Fragment(), OnMapReadyCallback {

private lateinit var googleMap: GoogleMap

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View {
    val view = inflater.inflate(R.layout.fragment_map, container, false)

    val supportMapFragment = SupportMapFragment()
    supportMapFragment.childFragmentManager.findFragmentById(R.id.google_map)
    supportMapFragment.getMapAsync(this)

    return view
   }
}

And fragment_map .xml file looks like:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/primaryBackground"
    xmlns:app="http://schemas.android.com/apk/res-auto">


       <androidx.fragment.app.FragmentContainerView
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/google_map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
1

There are 1 answers

0
tonileipo On

Adding:

private lateinit var mapFragment: SupportMapFragment

removing

val supportMapFragment = SupportMapFragment()

and changing

supportMapFragment.childFragmentManager.findFragmentById(R.id.google_map)

to

mapFragment = childFragmentManager.findFragmentById(R.id.google_map) as SupportMapFragment

fixes this