Search code examples
androidkotlinandroid-fragmentsandroid-dialogfragmentdialogfragment

Dialog Fragment Bundle always null


I just want to send data from Fragment to DialogFragment. In Fragment ;

 val fm = requireActivity().supportFragmentManager
            val dialog = DialogFragmentName()
            val arg :Bundle? =null
            arg?.putInt("num",75)
            dialog.arguments = arg
            dialog.show(fm,"TAG")

In DialogFragment ;

 val bundle :Bundle? = arguments
    if (bundle != null) {
        val number: Int? = bundle.getInt("num")
        Toast.makeText(context,number,Toast.LENGTH_LONG).show()
    } else {
        Toast.makeText(context,"Null",Toast.LENGTH_LONG).show()
    }

But it always gives me Null


Solution

  • You forgot to initialise your Bundle, it is set to null and trying to add data to null reference fails safely because of ?. operator which ends up sending empty Bundle

    val fm = requireActivity().supportFragmentManager
    val dialog = DialogFragmentName().apply{
          arguments = Bundle().apply{
              putInt("num",75)
          }
      }
    dialog.show(fm,"TAG")