Home > Back-end >  my app keeps crashing when using .apply although it has built successfully
my app keeps crashing when using .apply although it has built successfully

Time:12-15

Apologies if formatting or provided info is subpar my I have not asked a question on here before.

My Kotlin app crashes on load when it goes through a section of code inside a fragment using .apply. The code of the fragment responsible is below:

class SitesFragment : Fragment() {

    private var _binding: FragmentSitesBinding? = null
    private val binding get() = _binding!!

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

        gatherManga()

        val fragment = this
        //binding.recyclerView.apply{
        //    layoutManager = GridLayoutManager(activity,3)
        //    adapter= CardAdapter(mangaList)
        //}
    }

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

    override fun onDestroyView(){
        super.onDestroyView()
        _binding = null
    }

    //Currently hardcoded for testing
    private fun gatherManga(){
        val manga1 = Manga(
            R.drawable.slc,
            "Chu-Gong",
            "Solo-Leveling",
            "Webnovel.com",
        )
        mangaList.add(manga1)

    }

}

With the current code the app runs just fine but as soon as the .apply line is uncommented it successfully builds but crashes. Any idea on what I have done wrong or why this would be happening? The code is meant to display the mangaList in a recycler view inside the fragment.

CodePudding user response:

The onCreate method is called before the onCreateView and you are trying to access the recycler before it's initialized
Try moving the commented code into the onCreateView

More about fragment lifecycle here

  • Related