I have a 2D array of Enums I want to pass between two of my activities.
Currently I convert the 2D Enum array to a 2D int array, pass it to the Bundle, and on the other side convert it to a 1D Object array, then a 2D int array and finally back to my 2D Enum array.
Is there a better way to do this?
I have no problem passing single enums, after checking out Android: How to put an Enum in a Bundle?
I tried directly passing and retrieving the 2D Enum array, but I get a RuntimeException when I try to retrieve it.
Here's my code:
Passing the 2D array to the Bundle:
// Send the correct answer for shape arrangement
Intent intent = new Intent(getApplicationContext(), RecallScreen.class);
Bundle bundle = new Bundle();
// Convert mCorrectShapesArrangement (Shapes[][]) to an int[][].
int[][] correctShapesArrangementAsInts = new int[mCorrectShapesArrangement.length][mCorrectShapesArrangement[0].length];
for (int i = 0; i < mCorrectShapesArrangement.length; ++i)
for (int j = 0; j < mCorrectShapesArrangement[0].length; ++j)
correctShapesArrangementAsInts[i][j] = mCorrectShapesArrangement[i][j].ordinal();
// Pass int[] and int[][] to bundle.
bundle.putSerializable("correctArrangement", correctShapesArrangementAsInts);
intent.putExtras(bundle);
startActivityForResult(intent, RECALL_SCREEN_RESULT_CODE);
Retrieving out of the Bundle:
Bundle bundle = getIntent().getExtras();
// Get the int[][] that stores mCorrectShapesArrangement (Shapes[][]).
Object[] tempArr = (Object[]) bundle.getSerializable("correctArrangement");
int[][] correctShapesArrangementAsInts = new int[tempArr.length][tempArr.length];
for (int i = 0; i < tempArr.length; ++i)
{
int[] row = (int[]) tempArr[i];
for (int j = 0; j < row.length; ++j)
correctShapesArrangementAsInts[i][j] = row[j];
}
// Convert both back to Shapes[][].
mCorrectShapesArrangement = new Shapes[correctShapesArrangementAsInts.length][correctShapesArrangementAsInts[0].length];
for (int i = 0; i < correctShapesArrangementAsInts.length; ++i)
for (int j = 0; j < correctShapesArrangementAsInts[0].length; ++j)
mCorrectShapesArrangement[i][j] = Shapes.values()[correctShapesArrangementAsInts[i][j]];
Thanks in advance!