Pass an int array 2d to another activity

2

I have this array :

int[][] meuArray= new int[5][3];

How do I send this array to another activity?

If it was a array 1d just make intent.putExtra("Array", meuArray); to send and the array and do array = getIntent().getIntArrayExtra("Array"); to receive. But with a two-dimensional array this does not work.

    
asked by anonymous 09.12.2016 / 21:31

1 answer

3

The Intent class internally uses a Bundle to save the values passed to putExtra() method.

The class provides several versions (overloading) of the putExtra() method, including one that receives a serializable , as is the case for any type of Array .

When using

int[][] meuArray= new int[5][3];
...
...
intent.putExtras("meuArray", meuArray);

The overloaded method used is putExtra (String name, Serializable value) .

So, to retrieve the original array, you must use the method getSerializableExtra (String name) and not getIntArrayExtra (String name ) :

String[][] meuArray = (int[][])getIntent().getSerializableExtra("meuArray");

Note: It seems like a bug a> on Android 4 the error is thrown

  

java.lang.ClassCastException: java.lang.Object [] can not be cast to int [] []

When doing cast return method to int[][] .

If this is the case, use

Object[] vector;
int[][] meuArray;

vector = (Object[])getIntent().getSerializableExtra("meuArray");
meuArray = Arrays.copyOf(vector, vector.length, int[][].class);

to retrieve the array.

    
09.12.2016 / 22:32