How to use fragments with kotlin

Harol Rodriguez picture Harol Rodriguez · Jun 19, 2017 · Viewed 15.1k times · Source

I can not find how to use fragments using kotlin. I get an error in the onCreateView method, please help me.

ListaFragment.kt:

class ListaFragment : Fragment() {

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

    return view
}
}

fragment_lista.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:text="Hello"/>
</LinearLayout>

MainActivity.kt:

class MainActivity : AppCompatActivity() {

    private var listaFragment: ListaFragment? = null
    override fun onCreate(savedState: Bundle?) {
        super.onCreate(savedState) //cual es la diferencia con savedInstanceState
        setContentView(R.layout.activity_main)

        listaFragment = Fragment.instantiate(this@MainActivity,
                ListaFragment::class.java!!.getName()) as ListaFragment

        fragmentManager.beginTransaction().replace(R.id.flLista, listaFragment).commit()
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.example.harol.appfinalandroid.MainActivity">

    <FrameLayout
        android:id="@+id/flLista"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>

</LinearLayout>

I have no syntax errors, the application stops when I open the fragment

error:

Caused by: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter savedInstanceState
                                                                                     at com.example.harol.appfinalandroid.ListaFragment.onCreateView(ListaFragment.kt:0)

Answer

ianhanniballake picture ianhanniballake · Jun 19, 2017

savedInstanceState is nullable, yet you declared it as Bundle - it should be Bundle?.

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?): View? {