Search code examples
androidkotlinexceptionandroid-intentandroid-activity

Intents in Kotlin


So, I know that in Java we use this to launch new Activity:

Intent intent = new Intent(this, SomeActivity.class);
startActivity(intent);

But I'm writting a project using Kotlin and you use:

val intent = Intent(this, SomeActivity::class.java)
startActivity(intent)

But it crashes with this fatal exception:

FATAL EXCEPTION: main
Process: com.pashabred.passlin, PID: 15243
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pashabred.passlin/com.pashabred.passlin.Enterring}: kotlin.KotlinNullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                            Caused by: kotlin.KotlinNullPointerException
    at com.pashabred.passlin.Enterring.onCreate(Enterring.kt:17)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

Solution

  • Ensure you have a ? after Bundle:

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

    Instead of just Bundle:

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