I am implementing an app which uses GPS Location data , with a mapFragment integration. Inside the fragment, i am instantiating the mapFragment as this:
val mapFragment =
childFragmentManager.findFragmentById(com.example.sensorsapp.R.id.map_fragment) as com.google.android.gms.maps.MapFragment?
mapFragment!!.getMapAsync(this)
I am getting the exception mentioned bellow:
java.lang.NullPointerException
at com.example.sensorsapp.Fragments.MapFragment.fetchLocation$lambda-1
For some reason it fails to initialize the map object. What is the reason for this?
CodePudding user response:
Cast the map fragment to SupportMapFragment
instead of MapFragment
and make sure you retrieve the mapFragment in onCreateView
or onViewCreated()
val mapFragment =
childFragmentManager.findFragmentById(com.example.sensorsapp.R.id.map_fragment) as SupportMapFragment?
mapFragment?.let{it.getMapAsync(this)}
CodePudding user response:
More code from the application:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fetchLocation()
}
fetchLocation() is the function where the mapFragment is instantiated.
Within the activity layout, the framelayout that contains the fragment:
<FrameLayout
android:id="@ id/fragmentFrameLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@ id/buttonActionRelLayout">
<fragment
android:id="@ id/map_fragment"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>