SharedPreferences如何存取float数组
时间: 2023-06-08 16:04:50 浏览: 43
SharedPreferences可以使用putFloat和getFloat方法分别存取和获取float类型的值,但是SharedPreferences本身不能够存储float数组类型的值。可以将float数组转换为String类型进行存储,然后再在需要使用的地方进行转换。具体方法可以使用Arrays.toString进行转换,再使用SharedPreferences的putString和getString方法存取和获取值。
相关问题
SharedPreferences如何存取float数组,请给出一些代码参考
关于 SharedPreferences 存取 float 数组,可以使用 Gson 库将 float 数组转为 JSON 字符串并存储到 SharedPreferences 中。具体代码如下:
// 存储 float 数组
private void saveFloatArray(Context context, String key, float[] array) {
Gson gson = new Gson();
String json = gson.toJson(array);
SharedPreferences.Editor editor = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE).edit();
editor.putString(key, json).apply();
}
// 获取 float 数组
private float[] getFloatArray(Context context, String key) {
SharedPreferences prefs = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
String json = prefs.getString(key, null);
if (json != null) {
Gson gson = new Gson();
return gson.fromJson(json, float[].class);
}
return null;
}
调用方式如下:
float[] array = {1.0f, 2.0f, 3.0f};
saveFloatArray(context, "array_key", array);
float[] array = getFloatArray(context, "array_key");
如何使用SharedPreferences存储和读取 float数组
您可以使用SharedPreferences.Editor类中的putFloat()和getFloat()方法,将float数组存储为字符串,并将其保存在SharedPreferences中。以下是一个示例代码:
// 存储float数组
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
float[] floatArray = new float[]{1.5f, 2.5f, 3.5f};
String floatString = Arrays.toString(floatArray);
editor.putString("floatArray", floatString);
editor.apply();
// 读取float数组
SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
String savedString = preferences.getString("floatArray", "");
float[] savedFloats = Float.parseFloat(savedString.substring(1, savedString.length() - 1).split(", "));
// 注意:这种方法只适用于小型数组,对于大型数组,建议使用其他方法。