ASgames
ASgames

Reputation: 49

how to save float array in sharedpreferences?

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!

Upvotes: 2

Views: 738

Answers (2)

Afsar Ahamad
Afsar Ahamad

Reputation: 1997

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

Upvotes: 2

mahdi shahbazi
mahdi shahbazi

Reputation: 2132

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

Upvotes: 0

Related Questions