所以我有一个byte [] array
,我在我的Android应用程序中创建。我想使用Android的SharedPreferences存储它,并在我启动应用程序时再次检索它。我怎样才能做到这一点 ?
你可以尝试保存它有一个String
:
存储阵列:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("myByteArray", Arrays.toString(array));
检索数组:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String stringArray = settings.getString("myByteArray", null);
if (stringArray != null) {
String[] split = stringArray.substring(1, stringArray.length()-1).split(", ");
byte[] array = new byte[split.length];
for (int i = 0; i < split.length; i++) {
array[i] = Byte.parseByte(split[i]);
}
}
您可以使用android.util.Base64在SharedPreferences中保存字节数组。
保存:
String saveThis = Base64.encodeToString(array, Base64.DEFAULT);
装载:
byte[] array = Base64.decode(stringFromSharedPrefs, Base64.DEFAULT);
当你将它转换为Base64字符串时,你实际上是enlarge the size of a data。
Base64编码的二进制数据的最终大小等于原始数据大小的1.37倍+ 814字节(对于标题)。
使用Charsets.ISO_8859_1在SharedPreferences中保存byte []更快,内存效率更高
private static final String PREF_NAME = "SharedPreferences_Name";
private static final String DATA_NAME = "BytesData_Name";
public static byte[] getBytes(Context ctx) {
SharedPreferences prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
String str = prefs.getString(DATA_NAME, null);
if (str != null) {
return str.getBytes(Charsets.ISO_8859_1);
}
return null;
}
public static void setBytes(Context ctx, byte[] bytes) {
SharedPreferences prefs = ctx.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor e = prefs.edit();
e.putString(DATA_NAME, new String(bytes, Charsets.ISO_8859_1));
e.commit();
}
提示:如果你想节省更多的空间(如果保存巨大的字节[])压缩字节[],然后再将其转换为任何格式(ISO或Base64)
在共享首选项中保存数组:
public static boolean saveArray()
{
SharedPreferences sp = SharedPreferences.getDefaultSharedPreferences(this);
SharedPreferences.Editor mEdit1 = sp.edit();
mEdit1.putInt("Status_size", byteArr.size()); /* byteArr is an array */
for(int i=0;i<byteArr.size();i++)
{
mEdit1.remove("Status_" + i);
mEdit1.putString("Status_" + i, byteArr.get(i));
}
return mEdit1.commit();
}
从共享首选项加载阵列数据:
public static void loadArray(Context mContext)
{
Shared Preferences mSharedPreference1 = PreferenceManager.getDefaultSharedPreferences(mContext);
byteArr.clear();
int size = mSharedPreference1.getInt("Status_size", 0);
for(int i=0;i<size;i++)
{
byteArr.add(mSharedPreference1.getString("Status_" + i, null));
}
}
实现并调用上述2个函数。我希望上面的代码有所帮助
我不能赞成Ariel Yust的答案,但它完美无缺。
其他答案(如Base64编码器)不适用于我的最低API版本或未保留原始值(加密/解密数据时可能会出现问题)
作为补充,我建议在kotlin中使用扩展:
val String.toPreservedByteArray: ByteArray
get() {
return this.toByteArray(Charsets.ISO_8859_1)
}
val ByteArray.toPreservedString: String
get() {
return String(this, Charsets.ISO_8859_1)
}
然后你只需在你的字符串上调用它:
val string = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).getString("string", "") ?: ""
val byteArray = string.toPreservedByteArray