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
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.