Reputation: 2362
I have an Array
with integer values. It will grow over time. It will have approximately up to 50 values.
I want to store the array persistent and thus I thought about storing it in SharedPreferences
.
I know that no complex types can be stored in it, but I also heard about to serialise the Array
and then store it in SharedPreferences
.
Can someone give me a hint or even better sample code how to do that?
Upvotes: 1
Views: 5914
Reputation: 101
I would convert your array to a string of values separated by commas. And then store the string as a single key-value pair.
Then, when you want to extract the array, simple use the split function to split the string up into array elements based on a comma separator.
Upvotes: 1
Reputation: 10738
Not very efficient way, but will get the job done:
SharedPreferences prefs = ...;
final int count = 50;
final String KEY_COUNT = "COUNT";
final String KEY_VAL_PREFIX = "VAL_";
int values[] = new int[count];
/*
* ... put some stuff in values[] ...
*/
final Editor sped = prefs.edit();
sped.putInt(KEY_COUNT, count);
for (int i = 0; i < count; i++)
{
sped.putInt(KEY_VAL_PREFIX + i, values[i]);
}
sped.commit();
Then later you can retrieve these values by grabbing the KEY_COUNT value from the prefs, then filling your empty array with values2[i] = getInt(KEY_VAL_PREFIX + i, 0)
calls.
Upvotes: 4
Reputation: 66657
You may use ObjectSerializer to do it. Here is SO discussion on how to do.Store Shared preferences
Upvotes: 1