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?
Asked
Active
Viewed 5,902 times
1

CopsOnRoad
- 237,138
- 77
- 654
- 440

tobias
- 2,322
- 3
- 33
- 53
-
You can also refer to this [ANSWER](http://stackoverflow.com/questions/7175880/how-can-i-store-an-integer-array-in-sharedpreferences) – srujan maddula Feb 19 '14 at 06:19
3 Answers
4
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.

Josh
- 10,618
- 2
- 32
- 36
-
:Do you think you can help me with this?http://stackoverflow.com/questions/9209673/using-preferences-my-listview-is-empty-cant-store-data – George Feb 16 '12 at 12:52
-
@Josh can you include the whole code for the getter and setter? – HeartlessArchangel Jun 28 '13 at 23:54
1
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.

user3469294
- 101
- 1
- 3
1
You may use ObjectSerializer to do it. Here is SO discussion on how to do.Store Shared preferences