android编程使用onsaveinstancestate保存数组

时间:2014-04-02 16:17:20

标签: java android

我已经创建了一个非常好用的Android应用程序,但是当我将手机的位置更改为横向模式时,所有数据都会被重置,即游戏按钮上的所有文本都被空白值替换。 / p>

我正在尝试使用onSaveInstanceState(Bundle outState)方法来解决它

我必须保存一个三维字符数组(即我已经通过char[][][] a=newchar[3][3][3]声明了它)

我使用以下代码保存

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

但它会出现以下错误

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[][][])

2 个答案:

答案 0 :(得分:3)

数组是可序列化的。你可以尝试:

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
     }

}

答案 1 :(得分:2)

这可以在onSaveInstanceState(Bundle savedInstanceState)方法中存储数组:

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

然后在onRestoreInstanceState(Bundle savedInstanceState)方法中重新填充数组:

@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);
    }
//...
}