Save An Array Of Booleans Using Shared Preference
Solution 1:
In order to save an array of booleans to memory, I suggest you build a string from the booleans as follows:
Initialization
privateboolean[] checkState;
private Editor mEditPrefs;
private SharedPreferences mPreferences;
//initialize checkState array and mEditPrefs and mPreferences
Save the array
Stringsave="";
for (intn=0; n < checkState.length; n++) {
if (checkState[n] != null) {
if(checkState[n]) {
save = save + "true" + "|$|SEPARATOR|$|";
} else {
save = save + "false" + "|$|SEPARATOR|$|";
}
}
}
mEditPrefs.putString("memory", save);
mEditPrefs.commit();
Get the Array
String mem = mPreferences.getString("memory", "");
mEditPrefs.putString("memory", "");
String[] array = getArray(mem); //see below for the getArray() method
checkState = newboolean[array.length];
for(int n = 0; n < array.length; n++){
if(array[n].equals("true"){
checkState[n] = true;
} else {
checkState[n] = false;
}
}
the getArray() method
publicstaticString[] getArray(String input) {
return input.split("\\|\\$\\|SEPARATOR\\|\\$\\|");
}
This isn't an elegent solution, but SharedPreferences doesn't support storing arrays, so the only way to store an array is to make a long string separated by a discernible separator (in this case |$|SEPARATOR|$| ) that won't be confused with the data you are storing. Also, since there's no way to store arrays, I converted the booleans to strings before storing them and then I retrieve them from memory and detect if it is "true" or "false" and set the checkState array accordingly.
Hope this helped. I use a very similar process for storing an array of URLs and it works perfectly.
Alternatively you could use an SQLiteDatabase to store your array, but that might be a little too much work just to store some booleans.
EDIT: Originally I thought that toString() would work on a boolean, but apparently not on an array.
Post a Comment for "Save An Array Of Booleans Using Shared Preference"