0

I tried storing array list data by using serializable and parcelable but in both case when I get the data using getParcelable and getSerializable. I am getting error due to @Deprecated or Type Mismatch.

       val time1ArrayTennis: ArrayList<TimeArr>
       time1ArrayTennis = savedInstanceState?.getSerializable("time1") as ArrayList<*>

    //TimeArr is data class
      data class TimeArr(
          val time1 : Int
           ) : Serializable

Can someone please help how to in a simple way I can save and restore data when screen rotates? Thanks

1 Answers1

1

It's unclear what is TimeArr in your code snippet. Probably you're getting an error, because it doesn't implement Parcelable interface. So you have at least 2 options:

  1. Implement Parcelable interface for your TimeArr class. And then use outState.putParcelableArrayList("time1", time1ArrayTennis) to store your array in Actiivty.onSaveInstanceState() method. And then get it from Bundle after Activity's recreation in onRestoreInstanceState(savedInstanceState: Bundle)
  2. Save this data in ViewModel:

Your ViewModel class:

    class MyViewModel : ViewModel() {

        val time1ArrayTennis: ArrayList<TimeArr>

        .....

    }

Your Activity class:

    class MyActivity : AppCompatActivity() {

        private val viewModel: MyViewModel by viewModels()

        .........

        private fun someFunWhereYouWorkWithData() {
            val data = viewModel.time1ArrayTennis
            // TODO: work with data
        }

    }
Mikhail Guliaev
  • 1,168
  • 1
  • 6
  • 14
  • Hi, Thank you for helping. Can you provide a good reference for implementing Parcelable for Arraylist? – Satyam Raikwar May 03 '23 at 08:17
  • 1
    You need to implement Parcelable for your TimeArr. Just check out the official documentation: https://developer.android.com/reference/android/os/Parcelable – Mikhail Guliaev May 03 '23 at 08:49