I'm using Kotlin to make an android app, but I keep getting a NullPointerException
when trying to access a layout elements using Kotlin's android extensions. The code is a little bit complicated, so I'll try to explain the problem with a simple example.
Say I have a layout second_layout.xml
with a button and a textView:
<LinearLayout ...>
<TextView
android:id="@+id/textView"
..../>
<Button
android:id="@+id/button"
android:onClick="onButtonClicked"
... />
</LinearLayout>
In the main activity, I want to change the textView text when I click on the button:
import kotlinx.android.synthetic.main.second_layout.*
override fun onCreate(savedInstanceState: Bundle?) {
...
}
fun onButtonClicked(view: View) {
textView.text = "TextView text has changed"
}
Now when I click the button, Kotlin throw a NullPointerException, apparently the textView
property is null. I hope the above code is clear.
Does anyone have an idea what's going on? Did I do something wrong? Thanks.