1

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?

Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23

3 Answers3

1

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.

Timmmm
  • 88,195
  • 71
  • 364
  • 509
0

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

Community
  • 1
  • 1
Mojo Risin
  • 8,136
  • 5
  • 45
  • 58
0

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.

Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23