jicz jicz - 4 months ago 34
Android Question

How to add a Boolean Array in Shared preferences in Android

I want to store a Boolean array in Shared preferences ,and i want to access the array elements later. Can anybody help me ?.Thanks in advnc.

Answer

Store your array

public boolean storeArray(Boolean[] array, String arrayName, Context mContext) {   

    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    SharedPreferences.Editor editor = prefs.edit();  
    editor.putInt(arrayName +"_size", array.length);  

    for(int i=0;i<array.length;i++)  
        editor.putBoolean(arrayName + "_" + i, array[i]); 

    return editor.commit();  
}

Load your array

public Boolean[] loadArray(String arrayName, Context mContext) {  

    SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);  
    int size = prefs.getInt(arrayName + "_size", 0);  
    Boolean array[] = new Boolean[size];  
    for(int i=0;i<size;i++)  
        array[i] = prefs.getBoolean(arrayName + "_" + i, false);  

    return array;  
}
Comments