1

I have an integer two-dimensional array and I want to store it in SharedPreferences. Could someone show me sample code how to do that? I suppose it is possible if I will convert it to string but it works for one-dimensional integer array. Maybe other way is exist to do that? Thanks.

Denis Lolik
  • 299
  • 1
  • 4
  • 11

1 Answers1

2

As you said, converting to string that two-dimensional array will work. However if you face the same problem with more complex objects, you can always convert it to string using the GSON library.

Download: Link

Another post: Link

If you want to pass a two-dimensional array to string, you can iterate through it while storing it to a StringBuffer, as this example:

StringBuffer results = new StringBuffer();
String separator = ","
float[][] values = new float[50][50];

// init values

for (int i = 0; i < values.length; ++i)
{
  result.append('[');
  for (int j = 0; j < values[i].length; ++j)
    if (j > 0)
      result.append(values[i][j]);
    else
      result.append(values[i][j]).append(separator);
  result.append(']');
}

result.toString(); //<- Save this in your preference
Community
  • 1
  • 1
nsL
  • 3,722
  • 3
  • 23
  • 40
  • But how does it work for two-dimensional array? Could you give me sample code for it? – Denis Lolik Jan 29 '14 at 12:40
  • @user3248705 i've added a simple code to pass a two-dimensional array to string. In the backward way you should look for "[" , "]" and "," to fill again your array – nsL Jan 29 '14 at 12:50