Kotlin

2017-07-28 10 views
0
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:この行のKotlin

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) 

は、エラーが表示されている:あなたはそれに対処しなければならないので、NULL可能であることをmapFragmentを宣言し

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

はfragmentManager –

+0

それが直接 –

答えて

2

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

はい、それはあなたが 'val'する' mapFragment'を宣言することができることを利用して私のためのおかげでたくさん –

+0

を働いていたが使用されているそのgetFragmentManagerメソッドを初期化しました。一度割り当てただけで安全になり、別の値に再割り当てできなくなります。 IDEはおそらく、 – Pelocho

0

このエラーは、 nullSupportMapFragmentにキャストしようとしています。したがって、最初にタイプをチェックする方が安全です。

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