gi pi
gi pi

Reputation: 103

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?

Upvotes: 0

Views: 77

Answers (2)

Kamil Jeglikowski
Kamil Jeglikowski

Reputation: 192

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);
}

Upvotes: 2

Kristy Welsh
Kristy Welsh

Reputation: 8520

You need to implicitly declare the type of ArrayList:

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

The compiler has no idea otherwise when you're trying to do:

ArrayList myArrayList = outstate.getIntegerArrayList("My Key")

Upvotes: 1

Related Questions