存储阵列中的共享preferences

问题描述:

我有一个整数值数组。它会随时间而增加。这将有approximatelly多达50值。
我想存储阵列持续,因此我想到了将其存储在共享preferences。
我知道,没有复杂的类型可以存储在里面,但我也听说了序列化数组,然后将其存储在共享preferences。
有人可以给我一个提示,甚至更好样品code那怎么办?

I have an Array with integer values. It will grow over time. It will have approximatelly 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 serialize the array and then store it in sharedpreferences. Can someone give me a hint or even better sample code how to do that?

不是很有效的方法,但会完成这项工作:

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();

后来的后来,你可以通过从preFS敛KEY_COUNT值,则尽显你的空数组与 values​​2 [I] =调用getInt(KE​​Y_VAL_ preFIX + I,0检索这些值)通话。