Android Kotlin findViewById must not be null
As @Declan Nnadozie already mentioned: btnYES = findViewById(R.id.btnYES)
returns null
because btnYES
is not a view inside the contentView
inflated to PageTwoActivity
.
The buttons btnYES
and btnNO
and the EditText etStudentName
can be found in the content that is inflated in the dialog:
Also in Kotlin you do not need findViewById to access the activity's views.
You can delete all these:
internal lateinit var btnBACK: Button
internal lateinit var btnDIALOG: Button
internal lateinit var btnYES: Button
internal lateinit var btnNO: Button
internal lateinit var etStudentName:EditText
My suggestion is to use the below code:
class PageTwoActivity : AppCompatActivity() {
var EnteredText: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_page_two)
addListenerOnButtonBACK()
addListenerOnButtonDIALOG()
Toast.makeText(this@PageTwoActivity, "You are on Page Two",
Toast.LENGTH_LONG).show()
}
fun doCustom(v: View) {
val openDialog = Dialog(this)
openDialog.setContentView(R.layout.custom_dialog)
val btnYES = openDialog.findViewById<Button>(R.id.btnYES)
val btnNO = openDialog.findViewById<Button>(R.id.btnNO)
val etStudentName = openDialog.findViewById<EditText>(R.id.etStudentName)
openDialog.setCancelable(false)
btnYES.setOnClickListener(View.OnClickListener {
EnteredText = etStudentName.getText().toString().trim({ it <= ' ' })
if (EnteredText.isEmpty()) {
Toast.makeText(applicationContext, "Enter Your Name\n\n OR Click DECLINE", Toast.LENGTH_LONG).show()
return@OnClickListener
}
Toast.makeText(applicationContext, "Registered $EnteredText", Toast.LENGTH_SHORT).show()
openDialog.dismiss()
})
btnNO.setOnClickListener(View.OnClickListener {
EnteredText = ""
val intent = Intent(this@PageTwoActivity, MainActivity::class.java)
startActivity(intent)
openDialog.dismiss()
})
openDialog.show()
}