Exception: property should be initialized before get


#1

As the title said, i got exception when using the property in android fragment. I'm on M12 0.12.1230 I added presenter2 as comparison, when running i will commented out either presenter or presenter2.

I have this abstract class

public abstract class BaseFragment<P : Any, V : Any> : Fragment() {
  abstract val layoutId: Int

  public var presenter: P by Delegates.notNull()
  public var contentView: V by Delegates.notNull()

  override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
  return inflater?.inflate(layoutId, container, false)
  }
}


Then i created new class derived from above.

public class MyFragment : BaseFragment<MyPresenter, MyView>() {
  override val layoutId: Int
          get() = R.layout.mylayout
  private var presenter2: MyPresenter by Delegates.notNull()

  override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
  Log.d(“kotlin”, “onCreateView”)
  val view = super<FragmentCoordinator>.onCreateView(inflater, container, savedInstanceState)
  
  presenter = MyPresenter()
  presenter2 = MyPresenter()
  return view
  }

  override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
  Log.d(“kotlin”, “onViewCreated”)
  super<FragmentCoordinator>.onViewCreated(view, savedInstanceState)
  presenter.prepareInitialData() //work normally no exception thrown here
  presenter2.prepareInitialData() //work normally no exception thrown here
  }
  fun update() {
  Log.d(“kotlin”, “update fragment”)
  presenter.doTask() //throw exception property not initialized
  presenter2.doTask() //throw exception property not initialized
  }
}


Then i’m displaying this fragment together with other fragment inside ViewPager.
I called ‘update()’ function of MyFragment inside onPageSelected of OnPageChangeListener.

viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() {   override fun onPageSelected(position: Int) {   super.onPageSelected(position)   updateFragment(pagerAdapter.getItem(position))   } })

private fun updateFragment(fragment: Fragment) {
  when (fragment) {
           is MyFragment -> {
           fragment.update()
           }
  }
  }


In logcat i see this sequence:

onCreateView
onViewCreated
update fragment

exception message


Both presenter and presenter2 throw exception when called from activity.
I wonder why i got such exception? Even though i can call it inside onViewCreated.
Are my codes bad by design?


#2

I'm sorry to wasting your time.

But it’s my own mistake.
The problem was on pageAdapter.getItem() which return fragment with empty view.

Sorry for the noise.