Android - Declare and use views in Kotlin

Viewed 12113

I am trying to use kotlin for android and trying to declare Linearlayout like this:

internal var linlay_SuccessfulPayment : LinearLayout = null!!
internal var linlay_failPayment : LinearLayout

linlay_SuccessfulPayment = findViewById(R.id.linlay_SuccessfulPayment) as LinearLayout
linlay_failPayment = findViewById(R.id.linlay_failPayment) as LinearLayout

But in log I am getting this :

Caused by: kotlin.KotlinNullPointerException
                                                                         at com.example.activities.PaymentResult.<init>(Result.kt:14)
                                                                         at java.lang.Class.newInstance(Native Method)
                                                                         at android.app.Instrumentation.newActivity(Instrumentation.java:1096)
                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3122)
                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415) 
                                                                         at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                         at android.os.Looper.loop(Looper.java:148) 
                                                                         at android.app.ActivityThread.main(ActivityThread.java:7329) 
                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

Please help me out.

7 Answers

Just add kotlin extension in gradle.build and you don't need to initialize param:

apply plugin: 'kotlin-android-extensions'

I'm just starting with Kotlin and trying to learn it. I bind views like this:

var myBtn: Button = findViewById<Button>(R.id.btnMyButton) as Button

or

var btnLogin: Button = findViewById<Button>(R.id.btnLogin)

You can use apply plugin: 'kotlin-android-extensions' in your app level build.gradle for binding view without using the findViewById() boilerplate code.
e.g linlay_failPayment.setParams() // any thing you want with only view_id
For more information check this kotlin-view-binding

Related