I just switched to Kotlin from Java. Doesn't matter what language is, I don't want mess in my onCreate function. Therefore, I initialize my UI objects in a function. In Java, I was able to do that. I was declaring objects in global, and initializing them in my define function. But when I tried the same way to do that in Kotlin, I'm getting the following error:
Caused by: kotlin.UninitializedPropertyAccessException: lateinit property send has not been initialized
at com.example.kotlinalistirma.MainActivity.action(MainActivity.kt:24)
at com.example.kotlinalistirma.MainActivity.define(MainActivity.kt:34)
at com.example.kotlinalistirma.MainActivity.onCreate(MainActivity.kt:19)
Here's my MainActivity.kt:
class MainActivity : AppCompatActivity() {
lateinit var send: Button
lateinit var name : EditText
lateinit var soyisim : EditText
lateinit var textView : TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
define()
}
fun action(){
send.setOnClickListener{
textView.append(name.text.toString() + "\n")
textView.append(soyisim.text)
}
}
fun define(){
val send : Button = findViewById(R.id.sendButton)
val name : EditText = findViewById(R.id.name)
val surname : EditText = findViewById(R.id.surname)
val textView : TextView = findViewById(R.id.textView)
action()
}
}
And activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="name"
android:id="@+id/name"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="surname"
android:id="@+id/surname"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/sendButton"
android:text="send"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textSize="30dp"/>
</LinearLayout>