Android: how to save 2d int array during onSaveInstanceState?

3.4k views Asked by At

Exactly as the question title says, I'm trying to save a 2d int array during onSaveInstanceState, tried the obvious:

outState.putIntArray("matrix",matrix);

got:

Error:(58, 39) error: incompatible types: int[][] cannot be converted to int[]

What am I suppossed to do?

3

There are 3 answers

0
Mojo Risin On BEST ANSWER

There is no suitable method to store the matrix directly. But there are methods for storing one dimensional arrays. So what you are looking for is how to represent two dimensional array as one dimensional. Here is a good starting point on how to do that - Algorithm to convert a multi-dimensional array to a one-dimensional array

0
Artemio Ramirez On

As my array is only 2d I tried this approach:

For saving:

outState.putIntArray("matrix4x0",matrix4x4[0]);
outState.putIntArray("matrix4x1",matrix4x4[1]);
outState.putIntArray("matrix4x2",matrix4x4[2]);
outState.putIntArray("matrix4x3",matrix4x4[3]);

To retrieve:

matrix4x4[0] = savedInstanceState.getIntArray("matrix4x0");
matrix4x4[1] = savedInstanceState.getIntArray("matrix4x1");
matrix4x4[2] = savedInstanceState.getIntArray("matrix4x2");
matrix4x4[3] = savedInstanceState.getIntArray("matrix4x3");

It works, but I agree that for multidimensional arrays, converting to 1D array seems to be the correct way.

0
Timmmm On

You could convert it into a 1D array and store the row-lengths as a separate array. E.g. in pseudo-java:

int[] sizes;
int[] values;
for (int[] row : matrix)
{
    values.append(row);
    sizes.append(row.length);
}

outState.putIntArray("matrix_values", values);
outState.putIntArray("matrix_sizes", sizes);

I guess it's likely that your row sizes are all the same in which case you can use a single integer.