我有一个看起来像这样的数组:
String private String array[][];
array = [["smthng","smthng","smthng","smthng"],
["smthng","smthng","smthng","smthng"]];
我想将它转换为String来存储它,然后再将其转换为2D数组,但我总是得到indexoutboundexception。
我试过了:
private String twoDimensionalStringArrayToString(String[][] myArray) throws IOException {
String res = "";
for (int iRow = 0; iRow < myArray.length; iRow++) {
for (int iCol = 0; iCol < myArray[iRow].length; iCol++)
res += myArray[iRow][iCol] + ",";
res += "\n";
}
return res;
}
private String[][] stringToTwoDimensionalStringArray(String res) throws ClassNotFoundException, IOException {
String[] rows = res.split("\n");
String[][] myArray = new String[rows.length][];
for (int iRow = 0; iRow < rows.length-1; iRow++) {
String[] cols = rows[iRow].split(",");
myArray[iRow] = new String[cols.length];
for (int iCol = 0; iCol < cols.length; iCol++)
myArray[iRow][iCol] = cols[iCol];
}
return myArray;
}
然后我这样做来保存字符串:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("MAPA", twoDimensionalStringArrayToString(mapa));
这是为了阅读它:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mapa = stringToTwoDimensionalStringArray(sharedPref.getString("MAPA", null));