了解SharedPreferences
SharedPreferences是Android平台中一种轻量级的存储方式,主要用于保存简单的键值对数据。它是非关系型数据库的一种,相较于SQLiteDatabase,SharedPreferences的读写速度更快,且不需要设置数据库结构,非常适合用于保存临时性或轻量级的数据。
将数组存入SharedPreferences
在Android中,SharedPreferences只能直接存储String类型的键值对。因此,将数组存储在SharedPreferences之前,需要将其转换成String类型的字符串。
以下是将数组存储在SharedPreferences中的步骤:
步骤一:准备数据
首先,我们准备一个简单的数组,例如一个整数数组:
int[] dataArray = {1, 2, 3, 4, 5};
步骤二:数组转字符串
由于SharedPreferences不支持直接存储数组,我们需要将数组转换成字符串。以下是一个简单的数组转字符串的方法:
import java.io.IOException;
import java.util.Arrays;
public String arrayToString(int[] array) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
dataOutputStream.writeInt(array.length);
for (int i = 0; i < array.length; i++) {
dataOutputStream.writeInt(array[i]);
}
byte[] byteArray = byteArrayOutputStream.toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
步骤三:将字符串存储在SharedPreferences中
import android.content.Context;
import android.content.SharedPreferences;
public void saveIntArrayToSharedPreferences(Context context, String key, int[] dataArray) {
SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, arrayToString(dataArray));
editor.apply();
}
步骤四:从SharedPreferences中读取字符串并转换回数组
import android.content.Context;
import android.content.SharedPreferences;
public int[] getIntArrayFromSharedPreferences(Context context, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPreferences", Context.MODE_PRIVATE);
String jsonString = sharedPreferences.getString(key, null);
if (jsonString == null) {
return new int[0];
}
try {
byte[] byteArray = Base64.decode(jsonString, Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
int length = dataInputStream.readInt();
int[] resultArray = new int[length];
for (int i = 0; i < length; i++) {
resultArray[i] = dataInputStream.readInt();
}
return resultArray;
} catch (IOException e) {
e.printStackTrace();
return new int[0];
}
}
注意事项
1.SharedPreferences中的数据是持久化的,即使应用被杀死或设备重启,数据也不会丢失。 2.在读写SharedPreferences时,应确保当前线程为非UI线程。 3.SharedPreferences只能存储基本数据类型和String类型,如果需要存储复杂数据结构,请考虑使用SQLite等数据库。
通过以上步骤,你可以轻松地将数组存储在Android设备的SharedPreferences中。希望这篇教程能帮助你解决实际问题。
