Anuj
Anuj

Reputation: 1014

android programming saving array using onsaveinstancestate

I have created an android app it works perfectly fine,but when i change the position of my phone to landscape mode all the all data gets reset that is all the text on the buttons of the game gets replaced by blank values.

I am trying to use onSaveInstanceState(Bundle outState) method to solve it

I have to save a 3 dimensional Character array(i.e. i have declare it by char[][][] a=newchar[3][3][3])

I am using the following code to save it

    public void onSaveInstanceState(Bundle outState)
{
    outState.putCharArray(char[][][] "a", a);
    super.onSaveInstanceState(outState);
}

but it gives the following error

Multiple markers at this line
- Syntax error on token(s), misplaced construct(s)
- The method putCharArray(String, char[]) in the type Bundle is not applicable for the arguments (String, 
 char[][][])

Upvotes: 2

Views: 2915

Answers (2)

Ken Bushnell
Ken Bushnell

Reputation: 21

This worked storing an array in the onSaveInstanceState(Bundle savedInstanceState) method:

@Override
public void onSaveInstanceState(Bundle savedInstanceState)
{ 
    for (int count = 0; count < gameMovesArray.length; count++)
    {
    String gameMovesArrayCountString = "gamesMovesArray" + Integer.toString(count); //concatenated string
    savedInstanceState.putInt(gameMovesArrayCountString, gameMovesArray[count];
    } 
    //...
super.onSaveInstanceState(savedInstanceState);
}

Then to repopulate the array in the onRestoreInstanceState(Bundle savedInstanceState) method:

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) 
{
    super.onRestoreInstanceState(savedInstanceState);
    for(int count = 0; count < gameMovesArray.length; count++)
    {
    String gameMovesArrayCountString = "gamesMovesArray" + Integer.toString(count);
    gameMovesArray[count] = savedInstanceState.getInt(gameMovesArrayCountString);
    }
//...
}

Upvotes: 2

EL45
EL45

Reputation: 469

Arrays are serializable. You could try:

public void onSaveInstanceState(Bundle outState){
    char[][][] a=new char[3][3][3];
    outState.putSerializable("a", a);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
     char[][][] a = (char[][][]) savedInstanceState.getSerializable("a");

     if(a != null)
     {
          //Do something with a
     }

}

Upvotes: 3

Related Questions