0

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?

3
  • What is the type of ArrayList() for deck, cardchosen, deck1Image, deck2Image? Commented Feb 11, 2021 at 15:27
  • It´s all Integer ArrayList Commented Feb 11, 2021 at 15:28
  • I already tried with outstate.getIntegerArraylist but it gets red underline... Commented Feb 11, 2021 at 15:28

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

Where do I put the onSaveInstanceState? In MainActivity? Because class deck doesn't have OnCreate so there's nothing to overrider...
Yes, In your activity
Unfortunately need in java
Thanks! But how can I restore that data after reopening the app? Also in MainActivity? And if so, what's the best way to get my saved data back in my deck class?
1

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.