How to handle receiving null value from bundle

76 Views Asked by At

Hi I am passing a string to a fragment in a bundle and it can be null, but I am not sure how to accept null value when I read from the bundle argument

companion object {
    private const val KEY_CONTACT_P_NUM = "contact_p_num"
    fun newInstance(pNum: String?): GITFragment {
        return GetInTouchResponseFragment().apply {
            arguments = bundleOf(KEY_CONTACT_P_NUM to phoneNumber)
        }
    }
}

val pNum = arguments?.getString(KEY_CONTACT_P_NUM) as String

When I read the KEY_CONTACT_P_NUM from arguments I get an error Fatal Exception: java.lang.NullPointerException null cannot be cast to non-null type kotlin.String

How can I accept null value when I am reading from arguments

Thanks R

2

There are 2 best solutions below

0
dev.bmax On BEST ANSWER

You should remove the as String part in the last line.

The getString() method returns a nullable string (String?). But as String tries to convert it to a non-null string, which causes the exception.

0
BeNYaMiN On

In addition to @dev.bmax, to handle the argument you can do these approaches:

//Do something when the argument has value
requireArguments().getString(KEY_CONTACT_P_NUM)?.let { phoneNumber ->

}

//Assign an empty string when the argument is null
requireArguments().getString(KEY_CONTACT_P_NUM) ?: ""