-2

I need to store a 2d enum array in an sqlite database on Android so the easiest way seems to be to convert into a string (e.g. a CSV string) to store in the db and then back again when retrieving.

How can I do this in java?

MyEnum[][] myArray;

Thanks

fxfuture
  • 1,910
  • 3
  • 26
  • 40

1 Answers1

2

If you want to convert the whole 2d-array into a single String, you could use a CSV-type encoding, but you'd have to protect any special character (typ. the comma-separator) in order not to mess up field separation. A quick (and dirty?) way to do it would be to use enc = URLEncoder.encode(val, "UTF-8") on each value, and then back with val = URLDecoder.decode(enc, "UTF-8").

You would also have to use another separator (e.g. \n) to separate lines:

String write(MyENum[][] myArray) {
    String res = "";
    for (int iRow = 0; iRow < myArray.length; iRow++) {
        for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
            res += URLEncoder.encode(myArray[iRow][iCol].name(), "UTF-8")+",";
        res += "\n";
    }
}

(I'll let it to you not to add the extra "," at the end of each line). Then, to read back:

MyEnum[][] read(String res) {
    String[] rows = res.split("\n");
    MyEnum[][] myArray = new MyEnum[rows.length][];
    for (int iRow; iRow < rows.length; iRow++) {
        String[] cols = rows[iRow].split(",");
        myArray[iRow] = new MyEnum[cols.length];
        for (int iCol = 0; iCol < cols.length; iCol++)
            myArray[iRow][iCol] = MyEnum.valueOf(URLDecoder.decode(cols[iCol], "UTF-8"));
    }
    return myArray;
}

That is all based on the fact that there are name() and valueOf() methods available in your enum to make the transformation, as @sean-f showed you in the post he linked.

Matthieu
  • 2,736
  • 4
  • 57
  • 87
  • Thank you so much! Works perfectly. One little typo to note - this line should be String[] cols = rows[iRow].split(","); – fxfuture Jun 22 '13 at 20:30