Search code examples
androidkotlinandroid-fragmentsviewmodel

Viewmodel data lost on rotation


I've been using androids viewmodel for a project. At a point in my project I have two fragments that share a viewmodel. In fragment 1 (ManageListsFragment) the contents of the viewmodel are displayed and the user can navigate to fragment 2 (AddListFragment) where changes to the contents can be made. The fragments are contained in the same simple activity.

When doing changes in fragment 2, and then moving back to fragment 1, the changes are displayed no problem. However, when I rotate the screen in fragment 1, the changes made in fragment 2 are lost. What is going on? Doesn't the viewmodel persist and keep the changes?

Below is the essential code needed to understand my problem.

Fragment 1:


class ManageListsFragment : Fragment() {

    private lateinit var viewBinding: FragmentManageListsBinding
    private val lists: ListsViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_manage_lists, container, false)

        // Blah blah blah

        viewBinding.addListButton.setOnClickListener {
            findNavController().navigate(R.id.action_manageListsFragment_to_addListFragment)
        }
        return viewBinding.root
    }
}

Fragment 2:

class AddListFragment : Fragment() {

    private lateinit var lists: ListsViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        lists = ViewModelProvider(requireActivity()).get(ListsViewModel::class.java)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewBinding =
            DataBindingUtil.inflate(inflater, R.layout.fragment_add_list, container, false)
        // Blah blah blah

        return viewBinding.root
    }

    /***
     * Helper function for adding the list to the list of lists
     */
    private fun addList() {
        // Do changes to lists
        requireActivity().onBackPressed()
    }
}

Thanks in advance!


Solution

  • Solution was to let the underlying activity save the viewmodels data in it's onPause function.