javaandroidarraylistsaveonsaveinstancestate

How can I store Arraylists in class?


I have a class data, where I store my user data.

public class deck {
    public static ArrayList deck = new ArrayList();
    public static ArrayList cardchosen = new ArrayList();
    public static ArrayList deck1Image = new ArrayList();
    public static ArrayList deck2Image = new ArrayList();
}

How can I save the state of those Arrays in onSaveInstanceState? Do I have to use something different?


Solution

  • The easier would be to implement Serializable interface in your data class

    public class Deck implements Serializable {
    
        public static ArrayList deck = new ArrayList();
        public static ArrayList cardchosen = new ArrayList();
        public static ArrayList deck1Image = new ArrayList();
        public static ArrayList deck2Image = new ArrayList();
    }
    

    and then set bundle like that in onSaveInstanceState

    kotlin

        override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
            val deck = Deck()
            outState.putSerializable("mydeck", deck)
            super.onSaveInstanceState(outState, outPersistentState)
        }
    

    Java

    @Override
    public void onSaveInstanceState(Bundle outState) {
       outState.putSerializable("mydeck", deck);
       super.onSaveInstanceState(outState);
    }