0

in FragmentA() I get data from the previously Fragment

class FragmentA():Fragment() {
 private lateinit var personList: MutableList<Person>

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            personList = it.getParcelableArrayList<Person>("person") as MutableList<Person>
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      super.onViewCreated(view, savedInstanceState)

        if(personList.isEmpty()){
            showEmptyContainer()
        }else{
            recyclerAdapter.setItems(personList)
        }
}

Now, this code works when I open FragmentA(), but now, if I go from this fragment to FragmentB() and come back, my data is duplicated. So, I tried cleaning the array and set it up again

 class FragmentA():Fragment() {
     private lateinit var personList: MutableList<Person>
     private var backupList:MutableList<Person> = mutableListOf()

     override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            arguments?.let {
                personList = it.getParcelableArrayList<Person>("person") as MutableList<Person>
            }
        }

        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
          super.onViewCreated(view, savedInstanceState)

            if(personList.isEmpty()){
                showEmptyContainer()
            }else{
                backupList.clear()
                backupList = personList
                recyclerAdapter.setItems(backupList)
            }
    }

Doing this, it works when coming back, but, for some reason it shows the empty container when I do this twice so my question is

How can I retain this fragment personList while navigation forward and pressing the back button ?

Thanks

SNM
  • 5,625
  • 9
  • 28
  • 77

1 Answers1

1

You can use onSaveInstance and then check in onCreate if your savedInstanceState isn't null, here is a topic that will help you set it. onSaveInstanceState () and onRestoreInstanceState ()

Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • You can look at this link https://stackoverflow.com/questions/6525698/how-to-use-onsavedinstancestate-example-please, the accepted answer explain every step, as you're using a list of object, you'll have to use parcelable such as https://stackoverflow.com/questions/3172333/how-to-save-an-instance-of-a-custom-class-in-onsaveinstancestate – Biscuit Apr 02 '20 at 15:14
  • onSaveInstanceState is for the activity containing the fragment not the fragment itself – SNM Apr 02 '20 at 18:04
  • You can use the search of stackoverflow to help you out, look at this topic https://stackoverflow.com/questions/15313598/how-to-correctly-save-instance-state-of-fragments-in-back-stack – Biscuit Apr 02 '20 at 18:18