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