Johannes Gnadlinger Johannes Gnadlinger - 1 year ago 76
Android Question

How prevent to load onCreate of Fragment before Java?

Hey I tried to do this tutorial now I got the problem that when I start the app it crashes because the arguments of my fragment are null. I found an answer that I have to remove the fragment from my content_main.xml, but when I do this the app starts but behaves weird and I dont think this is the right answer for the problem.

So the onCreate() of my MainActivityFragment is called before the java code so I got problems with this lines:

override fun onCreate(savedInstanceState: Bundle?) {
page = this.arguments.getInt("someInt", 0)
title = this.arguments.getString("someTitle")

Whats the right solution for the problem?

My code is on github

Answer Source

According to your GitHub project, you are implementing Fragment instantiation in a wrong way. When you invoque var fragment = MainActivityFragment(), you create new Instance of your fragment but no arguments are provided, so, when your fragment onCreate method is called, arguments are null and that is the reason why your app crashes.

To fix your app crash you need to implement fragment instantiations on the following way:

MainActivityFragment (Edited)

// Wrap new instance function inside companion object
companion object {
    // newInstance constructor for creating fragment with arguments
    fun newInstance(page: Int, title: String): MainActivityFragment {
        val fragmentFirst = MainActivityFragment()
        val args = Bundle()
        args.putInt("someInt", page)
        args.putString("someTitle", title)
        fragmentFirst.arguments = args
        return fragmentFirst

 override fun onCreate(savedInstanceState: Bundle?) {
    if(null != this.arguments) {
        page = this.arguments.getInt("someInt", 1)
        title = this.arguments.getString("someTitle")


override fun getItem(position: Int): Fragment? {
    when (position) {
        0 // Fragment # 0 - Ensure to return a new fragment instance with valid arguments
        -> return MainActivityFragment.newInstance(0, "Page # 1")
        1 // Fragment # 0 - This will show FirstFragment different title
        -> return SecondFragment.newInstance(1, "Page # 2")
        else -> return null

Do not forget to wrap SecondFragment newInstance function within companion object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download