The AlertDialog(Material) crashes when tries to read the editText content.
The AlertDialog:
MaterialAlertDialogBuilder(activity)
.setTitle(title)
.setMessage(message)
.setView(R.layout.dialog_settings_entry)
.setPositiveButton(getString(R.string.text_change)) { dialog, which ->
etUserInput.hint = message
sgr = etUserInput.text.toString() // << crashes here
dialog.dismiss()
}
.setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
.show()
On clicking the positive button results as follows:
java.lang.IllegalStateException: etUserInput must not be null
at com.home.profile.SettingsFragment$buildAlertDialog$1.onClick(SettingsFragment.kt:332)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
The etUserInput is simple editText in a seperate layout. Unsure the crash reason. Would appreciate any insight into it or any helpful Material samples.
This Builder must be used in order for AlertDialog objects to respond to color and shape theming provided by Material themes. The type of dialog returned is still an AlertDialog; there is no specific Material implementation of AlertDialog . public MaterialAlertDialogBuilder (Context context, int overrideThemeResId)
Alternatively, there exists a secondary MaterialAlertDialogBuilder constructor which accepts an overriding theme resource ID: Material Alert Dialogs can be themed in terms of the three Material Theming subsystems: color, typography and shape. We have already shown which theme overlays to use in the “Choosing a theme overlay” section above.
Set the positive and the negative button using setPositiveButton () and setNegativeButton () respectively. Perform all the operations inside the click listener of the Positive button, such as extracting values from the edit texts. Don’t forget to call show () method on the MaterialAlertDialogBuilder instance, else your dialog won’t be shown at all.
activity_alert_dialog_custom_view_login_form.xml, this is the custom view layout XML file. It is saved in the app/res/layout folder. <!-- User name row. -->
Cast the DialogInterface
to an AlertDialog
and then use findViewById
.
Kotlin:
val et = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)
val text = et?.text.toString()
--
Java:
EditText et = ((AlertDialog)dialog).findViewById(R.id.etUserInput);
String text = et.getText().toString();
--
MaterialAlertDialogBuilder(activity)
.setTitle(title)
.setMessage(message)
.setView(R.layout.dialog_settings_entry)
.setPositiveButton(getString(R.string.text_change)) { dialog, which ->
val text = (dialog as? AlertDialog)?.findViewById<EditText>(R.id.etUserInput)?.text?.toString()
dialog.dismiss()
}
.setNegativeButton(getString(android.R.string.cancel)) { dialog, _ ->
dialog.dismiss()
}
.show()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With