title: Convert 2D array to String and String to 2D String again in Java
body: <p>I have an array looking like this:</p>
  
  <pre><code>String private String array[][];
  
  array = [["smthng","smthng","smthng","smthng"],
  ["smthng","smthng","smthng","smthng"]];
  </code></pre>
  
  <p>I want to convert it to String to store it and then convert it to 2D array again but I always get indexoutboundexception.</p>
  
  <p>I tried this:</p>
  
  <pre><code>private String twoDimensionalStringArrayToString(String[][] myArray) throws IOException {
      String res = "";
      for (int iRow = 0; iRow &lt; myArray.length; iRow++) {
          for (int iCol = 0; iCol &lt; 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 &lt; rows.length-1; iRow++) {
          String[] cols = rows[iRow].split(",");
          myArray[iRow] = new String[cols.length];
          for (int iCol = 0; iCol &lt; cols.length; iCol++)
              myArray[iRow][iCol] = cols[iCol];
      }
      return myArray;
  }
  </code></pre>
  
  <p>Then I do this to save the String:</p>
  
  <pre><code>SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = sharedPref.edit();
  editor.putString("MAPA", twoDimensionalStringArrayToString(mapa));
  </code></pre>
  
  <p>And This to read it:</p>
  
  <pre><code>SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
  mapa = stringToTwoDimensionalStringArray(sharedPref.getString("MAPA", null));
  </code></pre>