Pass int array 2d to another Activity

Asked

Viewed 226 times

2

I have this array:

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

How do I send this array for another activity?

If it were a array 1d was enough to make intent.putExtra("Array", meuArray); to send and the array and make array = getIntent().getIntArrayExtra("Array"); to receive. But with a array two-dimensional this no longer works.

1 answer

3


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

The class offers several versions (overloading/overload) of the method putExtra(), among them one who 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 that there is a "bug" on Android 4 that is released error

java.lang.Classcastexception: java.lang.Object[] cannot be cast to int[][]

in making cast return of the method to int[][].

If so, use

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

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

to retrieve the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.