Android kotlin.TypeCastException: null нельзя преобразовать в ненулевой тип com.google.android.gms.maps.SupportMapFragment

Я пытаюсь закодировать свое текущее приложение в Kotlin, но получаю, что значение null не может быть приведено к ненулевому типу. Я пробовал много разных вещей, но у меня все та же проблема. Не знаю, что делать. Любая помощь будет оценена по достоинству!

Код:

class MapsActivity : AppCompatActivity(), OnMapReadyCallback {

private lateinit var mMap: GoogleMap
private lateinit var button: Button

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_maps)

    val mapFragment = supportFragmentManager
            .findFragmentById(R.id.mapFragment) as SupportMapFragment
    mapFragment.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap) {
    mMap = googleMap;
    setUpMap();
}

fun setUpMap() {

    val et = findViewById<EditText>(R.id.editText);
    val et2 = findViewById<EditText>(R.id.editText2);
    val lat = et.getText().toString().toDouble();
    val lng = et2.getText().toString().toDouble();
    //val ll = LatLng(lat, lng)

    button = findViewById(R.id.button) as Button
    button.setOnClickListener {
        goToLocation(lat, lng, 11.0f);
    }
}

fun goToLocation(lat:Double, lng:Double, zoom:Float) {
    val ll = LatLng(lat, lng);
    val update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
    mMap.addMarker(MarkerOptions().position(ll).title("Marquette, Michigan"))
    mMap.moveCamera(update);
}

XML:

<LinearLayout 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:orientation="vertical"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
tools:layout="@layout/activity_maps">

<EditText
    android:id="@+id/editText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName" />

<EditText
    android:id="@+id/editText2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="textPersonName" />

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Submit"/>
    <!-- android:onClick="locate"/> -->

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

Logs:

Вызвано: kotlin.TypeCastException: null не может быть приведен к ненулевому типу com.google.android.gms.maps.SupportMapFragment в com.example.nrice.mapsproject.MapsActivity.onCreate(MapsActivity.kt:38)


person Nate    schedule 29.11.2018    source источник
comment
см. kotlinlang.org/docs/reference/null-safety.html об обнулении типы   -  person leonardkraemer    schedule 30.11.2018


Ответы (5)


Попробуй это

val mapFragment = childFragmentManager.findFragmentById(R.id.map_frag) as SupportMapFragment

mapFragment.getMapAsync(this)
person Lakshman Jodhawat    schedule 03.10.2019
comment
это работает для меня, я использую MapFragment внутри Fragment, поэтому childFragmentManager хорошо справляется со своей задачей вместо supportFragmentManager, спасибо! - person Roman; 22.12.2019
comment
это ответ, который вы ищете: stackoverflow.com/a/38405063/2445763; не использовать как? если вы не ожидаете нулевое значение - person lasec0203; 08.04.2020

Ошибка компиляции указывает на следующую строку в вашем коде:

val mapFragment = supportFragmentManager
            .findFragmentById(R.id.mapFragment) as SupportMapFragment

Здесь вы приводите тип чего-то, что допускает значение NULL, то есть возвращаемое значение findFragmentById, к чему-то, что вы определили как ненулевой тип, то есть SupportMapFragment

В идеале вам следует прочитать об обработке нулей в Kotlin. Это быстро читается, не требует времени и прояснит ваше понимание здесь.

И когда вы вернетесь, вы увидите, что существует более одного способа исправить ваш код, например:

(activity.supportFragmentManager.findFragmentById(fragmentId) as SupportMapFragment?)?.let {
    it.getMapAsync(this)
}

Подсказка: разница между типом, допускающим значение NULL, и типом, не допускающим значение NULL, в Kotlin заключается в постфиксе ? к типу. Итак, здесь SupportMapFragment? указывает, что тип SupportMapFragment и может быть нулевым.

person codeFood    schedule 30.11.2018

val mapFragment = supportFragmentManager.findFragmentById(R.id.mapFragment) as? SupportMapFragment
mapFragment?.getMapAsync(this)

Для справки вы должны прочитать это

person Mauro Curbelo    schedule 30.11.2018

если вы используете SupportMapFragment во фрагменте, вам нужно написать оператор childFragmentManager.findFragmentById(R.id.myMap) в

override fun onViewCreated(view: View, savedInstanceState: Bundle?)

не в

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
person Abd-Elwahab Zayed    schedule 20.01.2021
comment
хотя это не ответ, связанный с вопросом. но кто-то вроде меня получил точное решение, потому что я использую фрагмент. Благодарю. вот почему я голосую за тебя. - person Rezaul Karim; 02.02.2021
comment
приветствуются. - person Abd-Elwahab Zayed; 04.02.2021

исправить здесь, в котлине

private lateinit var mMap: GoogleMap


 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val mapFragment: SupportMapFragment? = map as SupportMapFragment?
    mapFragment?.getMapAsync(this)
}

override fun onMapReady(googleMap: GoogleMap?) {

    if (googleMap != null) {
        mMap = googleMap
    }

    val sydney = LatLng(-34.0, 151.0)
    mMap.addMarker(MarkerOptions().position(sydney).title("Marker in Sydney"))
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))
}
person Diego Souza    schedule 19.07.2020