2

I have float array I need to save this array in 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!

Eugene Ogongo
  • 335
  • 3
  • 12
ASgames
  • 49
  • 2

2 Answers2

2

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. 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

Afsar edrisy
  • 1,985
  • 12
  • 28
  • Hey @ASgames check [this](https://github.com/afsaredrisy/ArrayInSharedPref) Complete working project with this method. – Afsar edrisy Jan 25 '20 at 14:53
0

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;
    }
mahdi shahbazi
  • 1,882
  • 10
  • 19