1
votes

Why is my fragment not entering onCreateView when the variable is declared only in onCreate?

It only tells me "lateinit property beatBox has not been initialized" But it is!

beatBox is delared as a lateinit at the class level and defined in onCreate but the program does not enter the onCreateView method. I can put a Log.d in it and check the object type that is created! It crashes unless I redefine var beatBox, making a reference to a new object.

Why will my fragment not enter onCreateView?

class BeatBoxFragment : Fragment() {

    private lateinit var beatBox: BeatBox

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        var beatBox = BeatBox(requireContext())
        Log.d("Crashing", beatBox.toString() + " has been created, yer program does not go into onCreateView")
    }
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
    //var beatBox = BeatBox(requireContext())
    Log.d("Crashing", "The program does not enter onCreateView unless I uncomment the beatBox definition!)

    }

}
2

2 Answers

3
votes

The problem is... that you redeclare beatBox:

private lateinit var beatBox: BeatBox

fun test() {
    var beatBox = BeatBox() // Create new beatbox for `test() scope`.
                            // beatBox for class scope is still uninitialized.
}

So, just get rid of var keyword in onCreate ;)

0
votes

You are trying to declare beatbox object twise using. so remove var which you declare inside oncreate method.

 var beatBox = BeatBox(requireContext())  

Replace above code with

beatBox = BeatBox(requireContext())

See your Mistake which i highlight so remove var from oncreate method