0

Before I begin, I have read similarly worded posts like this one, but they are not working for me.

As I explain in the title, I get an NPE when I click the positive button ("ok" in this case). If anybody can point out what I am doing incorrectly that'll be great! Below is a abstracted version of my setup

MainFragment.kt

class MainFragment: DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?) =
            AlertDialog.Builder(context!!)
                .setView(FragmentMainBinding.inflate(LayoutInflater.from(context)).root)
                .setTitle(R.string.title_main)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ok) { _, _ -> onPositiveButtonTapped() }
                .create()

    private fun onPositiveButtonTapped() {
        val g = arrayListOf(ground_nbr_edit_text.text.toString()) // NullPointerException
        // ...
    }

}

fragment_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:id="@+id/ground_nbr_edit_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>
</layout>
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
El Sushiboi
  • 428
  • 7
  • 19

1 Answers1

1

DialogFragment calls onCreateView() after onCreateDialog() and then uses that view for the dialog's content, replacing whatever you had already set in onCreateDialog(). So move your view creation into onCreateView():

class MainFragment: DialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?) =
        FragmentMainBinding.inflate(inflater).root

    override fun onCreateDialog(savedInstanceState: Bundle?) =
            AlertDialog.Builder(context!!)
                .setTitle(R.string.title_main)
                .setNegativeButton(R.string.cancel, null)
                .setPositiveButton(R.string.ok) { _, _ -> onPositiveButtonTapped() }
                .create()

    private fun onPositiveButtonTapped() {
        val g = arrayListOf(ground_nbr_edit_text.text.toString()) // NullPointerException
        // ...
    }

}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154