Kotlin with Map in Android

2019-08-24 22:08发布

问题:

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
var view: View = inflater?.inflate(R.layout.map_fragment, null)!!

var mapFragment : SupportMapFragment?=null
mapFragment= fragmentManager.findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)

return view
}

Logcat :

FATAL EXCEPTION: main
kotlin.TypeCastException: null cannot be cast to non-null type 
com.google.android.gms.maps.SupportMapFragment
at example.com.kotlinexamplebydimple.Mapfragment.onCreateView(Mapfragment.kt:36)

on this line the error is showing :

mapFragment= fragmentManager.findFragmentById(R.id.map) as SupportMapFragment

回答1:

You declared mapFragment to be nullable so you have to deal with it:

var mapFragment : SupportMapFragment?=null
mapFragment = fragmentManager.findFragmentById(R.id.map) as SupportMapFragment?
mapFragment?.getMapAsync(this)


回答2:

The error implies that you try to cast a null to SupportMapFragment. So, it will be safer to check the type first.

val mapFragment = fragmentManager.findFragmentById(R.id.map)
if (mapFragment is SupportMapFragment) {
    mapFragment.getMapAsync(this)
}