WISHY
WISHY

Reputation: 11999

calling Fragment constructor caused an exception, kotlin?

I am using navigationcontroller to navigate to another fragment

Navigate to second fragment

private fun moveToNextScreen(userId: String) {
    val bundle = bundleOf("userId" to userId)
    binding.googleLogin.findNavController().navigate(
        R.id.action_loginFragment_to_signupFragment, bundle
    )
}

The fragment I am navigating to

class UserSetupFragment : Fragment() {
private lateinit var binding: FragmentUserSetupBinding

var optionCb = mutableListOf<AppCompatCheckBox>()
var optionsList =
    ArrayList<String>(Arrays.asList(*resources.getStringArray(R.array.profile_options)))

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    binding = FragmentUserSetupBinding.inflate(inflater, container, false)
    return binding.getRoot()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    createOptionsCheckBox()
}

private fun createOptionsCheckBox() {
    for (option in optionsList) {
        val checkBox = AppCompatCheckBox(activity)
        checkBox.setText(option)
        checkBox.setTextColor(ContextCompat.getColor(requireActivity(), android.R.color.black));
        optionCb.add(checkBox)
        binding.optionsLayout.addView(checkBox)
    }
}

}

I am getting the exception

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=66957, result=-1, data=Intent { (has extras) }} to activity {com.patient.reach52/com.patient.reach52.view.authenticate.AuthenticateActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.patient.reach52.view.authenticate.UserSetupFragment: calling Fragment constructor caused an exception

What is wrong over here?

Upvotes: 16

Views: 16084

Answers (3)

Eugene Babich
Eugene Babich

Reputation: 1689

In my case the problem was with Dagger2 injects. I've forgot to call the build of component in one of modules.

Upvotes: 0

Kirguduck
Kirguduck

Reputation: 796

previous comments are right about reason - you are trying to access resources too early
but i didn't see a right solution
avoid to use lateinit
for current situation try

val optionsList by lazy {
        resources.getStringArray(R.array.profile_options).toList()
    }

Upvotes: 2

Andrei Tanana
Andrei Tanana

Reputation: 8432

You cannot access resources until the fragment will be attached to an activity. So you have to delay instantiation of optionsList

class UserSetupFragment : Fragment() {
    lateinit var optionsList: List<String>

    override fun onAttach(context: Context) {
        super.onAttach(context)
        optionsList = resources.getStringArray(R.array.profile_options).toList()
    }
...

Upvotes: 23

Related Questions