【问题标题】:how to save float array in sharedpreferences?如何在共享首选项中保存浮点数组?
【发布时间】:2020-01-25 09:42:18
【问题描述】:

我有浮点数组 我需要将此数组保存在 sharedpreferences 中

float[] arrayx = new float[1000];

并在下次登录应用时再次获取此数组,

我该怎么做?

提前致谢!

【问题讨论】:

标签: java android-studio


【解决方案1】:

最简单的方法可能是将 float[] 转换为逗号分隔的字符串并保存到共享首选项,而检索它可以是 split(",") 可以解析为浮动。如下。

    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;
    }



对于完整的工作项目,您可以查看this-repository

【讨论】:

  • 嘿 @ASgames 检查 this 使用此方法完成工作项目。
【解决方案2】:

看看这个

使用它,您可以使用索引更快地访问每个项目

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;
    }

【讨论】:

    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 2017-08-19
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多