Home > Software design >  Why navigation still error after passing the necessary parameter?
Why navigation still error after passing the necessary parameter?

Time:11-18

I have 3 fragments (A,B,C), the flow is like this : A -> B <-> C. I want fragment B only receive argument from fragment C, but I got error on Fragment A that says I have to pass an argument when navigate from fragment A to B. So to avoid that error, I pass 0 (i.e. the argument type is integer).

But even after I pass 0, I still get error on the line code that will navigate me from fragment A to B.

Here is my fragment B:

private val args: GameFragmentArgs by navArgs()
private var questionIndex = args.getQuestionIndexFromGameOverFragment

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {       
        val binding = DataBindingUtil.inflate<FragmentGameBinding>(
                inflater, R.layout.fragment_game, container, false)               
        binding.game = this   
        timer(binding)        

    return binding.root
}

I don't know why it gets error and how can I fix it?

CodePudding user response:

Here's the problem:

private var questionIndex = args.getQuestionIndexFromGameOverFragment

You call the arguments too early, they're not there yet. The solution would be to delay assigning the questionIndex value, for example with lazy:

private val questionIndex by lazy { args.getQuestionIndexFromGameOverFragment }
  • Related