Search code examples
android-studiokotlinnavigationfragment

my app is not working and keeps stopping. How can I fix this?


My app is not working and keeps stopping. How can I fix this issue? This is my first fragment code.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
}

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

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

    start2BT.setOnClickListener {
        Navigation.findNavController(it).navigate(Start1FragmentDirections.actionStart1ToStart2())
    }
}

When I run my app this happens. error message! I hope you understand where the problem is.

I don't know where the problem is from.


Solution

  • you need to post the log cat error. but from your class, I found that you didn't define and initialize the view but you are calling an onClick listener on it. i mean this line:

     start2BT.setOnClickListener {
            Navigation.findNavController(it).navigate(Start1FragmentDirections.actionStart1ToStart2())
        }
    

    you need to have something like this before that line

    var start2BT = (Button)view.findViewByID(R.id.start2BT)
    

    keep in mind that this was for a button. you can define and initialize the button on the onCreateView and also change

    return inflater.inflate(R.layout.fragment_start1, container, false)
    

    to this

    var view =  inflater.inflate(R.layout.fragment_start1, container, false)
    return view