'Saving object in android in onSaveInstanceState()

This is a puzzle app. I have a class of Puzzle that contains the object itself and business logics. In onCreate, I created the object itself, I need to save the instance. Is it a good idea to save the same object I created in onCreate in onSaveInstanceState()? If so, what is the best way to do it? Otherwise, should I save the variables of the object Puzzle in onSaveInstanceState()?

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Read in the arrays
        String[] targetWords = getResources().getStringArray(R.array.target_words);
        String[] okWords = getResources().getStringArray(R.array.acceptable_words);

        // TODO: Now we always create a new puzzle when the Activity is created. You
        // will need to restore the existing activity if the Framework has destroyed
        // and recreated it.
        newPuzzle = new Puzzle(targetWords, okWords);
        for (int i = 0; i < newPuzzle.getGuessCount(); i++) {
            displayResult(i);
        }
    }

    // save the puzzle obj?
    @Override
    public void onSaveInstanceState(Bundle outState){
        super.onSaveInstanceState(outState);
        

    }


Solution 1:[1]

Make your Puzzle Object Parcelable or Serializable, then save it in:

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

You can retrieve it in onCreate()

if (savedInstanceState != null) {
        newPuzzle = (Puzzle) savedInstanceState.getSerializable("puzzleObj");
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1