Skip to content

Saving byte array using SharedPreferences

So I have a byte [] array which I have created in my android app. I want to use SharedPreferences from android to store it and retrieve it back again when I start my app. How can I do that ?

Answer

You could try to save it has a String:

Storing the array:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("myByteArray", Arrays.toString(array));

Retrieving the array:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String stringArray = settings.getString("myByteArray", null);

if (stringArray != null) {
    String[] split = stringArray.substring(1, stringArray.length()-1).split(", ");
    byte[] array = new byte[split.length];
    for (int i = 0; i < split.length; i++) {
      array[i] = Byte.parseByte(split[i]);
    }
}