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.

1
  • You can convert 2 dimension array to string and back too. Commented Jan 29, 2014 at 12:28

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

But how does it work for two-dimensional array? Could you give me sample code for it?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.