App crashes when returing to MainActivity after screen rotation

221 Views Asked by At

When i go from MainActivity to EditTaskActivity (a screen where you can edit task options), rotate the screen and then try to save the task, the app crashes.

Now i found out that it crashes inside MainActivity's onActivityResult, when trying to save the task's data into sectionsPagerAdapter.tasks, because "tasks" is null.

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == RequestType.REQUEST_ADD_ITEM.ordinal) {
        if (resultCode == Activity.RESULT_OK) {
                //This is where it crashes
                sectionsPagerAdapter.tasks.addItem(Task(data?.getStringExtra("name") as String, 
                    data.getLongExtra("dueDate", 0)
                ))
            }
        }...

SectionsPagerAdapter (a FragmentPagerAdapter) is created inside MainActivity onCreate, so that is fine.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
    val viewPager: ViewPager = findViewById(R.id.view_pager)
    viewPager.adapter = sectionsPagerAdapter
    val tabs: TabLayout = findViewById(R.id.tabs)
    tabs.setupWithViewPager(viewPager)

The problem is that tasks are created inside the instantiateItem function, which for some reason gets called after the onActivityResult. Is there anything i can do, so that instantiateItem gets called before the onActivityResult?

class SectionsPagerAdapter(private val context: Context, fm: FragmentManager)
: FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
lateinit var tasks: ListFragment

override fun getItem(position: Int): Fragment {
    return ListFragment.newInstance(position)
}

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val fragment: ListFragment = super.instantiateItem(container, position) as ListFragment

    tasks = fragment

    return fragment
}

I feel like i've tried everything - calling getItem(), changing to FragmentStatePagerAdapter and saving it's state, but nothing works and the app still crashes. I'm clueless on this one, so any help will be greatly appreciated :)

0

There are 0 best solutions below