[英]how to save float array in sharedpreferences?
I have float array I need to save this array in sharedpreferences我有 float 数组,我需要将此数组保存在 sharedpreferences 中
float[] arrayx = new float[1000];
and get this array again in the next log in to app,并在下次登录应用程序时再次获取此数组,
how I can do it?我该怎么做?
Thanks in advance!提前致谢!
Easiest way could be to convert float[]
to a comma separated String & save to shared pref , While retrieving it can be split(",")
can parse to float.最简单的方法可能是将
float[]
转换为逗号分隔的 String 并保存到共享 pref ,而检索它可以是split(",")
可以解析为浮动。 as follows.如下。
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
public void saveFloatArray(float[] arr){
String str = " ";
for(int i=0;i<arr.length;i++){
str = str + ", "+ String.valueOf(arr[i]);
}
editor.putString("FLOAT_ARR",str);
editor.commit();
}
public float[] getFloatArray(){
String str = pref.getString("FLOAT_ARR", null);
if(str!=null){
String str1[] = str.split(",");
float arr[] = new float[str1.length-1];
// at i=0 it is space so start from 1
for(int i=1;i<str1.length;i++){
arr[i-1]=Float.parseFloat(str1[i]);
}
return arr;
}
return null;
}
For complete working project you can check this-repository对于完整的工作项目,您可以检查此存储库
Take a look at this看看这个
Using this you can access to each item using index very faster使用它,您可以更快地使用索引访问每个项目
SharedPreferences sharedPreferences=context.getSharedPreferences("name", 0);;
public void setFloatArrays(float[] arrays) {
final SharedPreferences.Editor editor = this.sharedPreferences.edit();
for (int i = 0; i < arrays.length; i++) {
editor.putFloat("float" + i, arrays[i]);
}
editor.apply();
}
public float[] getFloatArrays() {
float[] arrays = new float[1000];
for (int i = 0; i < arrays.length; i++) {
arrays[i] = this.sharedPreferences.getFloat("float" + i, 0f);
}
return arrays;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.