Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 295
jicz Avatar asked Apr 01 '26 18:04

jicz


2 Answers

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;  
}
like image 76
Rami Avatar answered Apr 08 '26 15:04

Rami


Store your array globally set checkbox value

 public boolean setCheckboxarray(Context mContext,Boolean[] array) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt(CHECKBOXARRAY, array.length);

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

    return editor.commit();
}

Load your array globally get checkbox value

public Boolean[] getCheckboxarray(Context mContext) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    int size = prefs.getInt(CHECKBOXARRAY, 0);
    Boolean array[] = new Boolean[size];
    for(int i=0;i<size;i++)
        array[i] = prefs.getBoolean(CHECKBOXARRAY+ i, false);

    return array;
}
like image 22
MalhotraUrmil Avatar answered Apr 08 '26 15:04

MalhotraUrmil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!