Store ProtoBuf object in SharedPreferences

I want to store an object ProtoBuf

in SharedPreferences

. Protocol Buffers

allows parsing from ByteString

or Byte Array

. But it SharedPreferences

doesn't. I was wondering if there is a way to do this without first creating another serializable model and matching.

I tried this way, but I get InvalidProtocolBufferException

:

public static void setProtoData(ProtoData data) {
    Prefs.putString(Constants.SHARED_PREF_PROTO_DATA, String.valueOf(data.toByteString()));
}

public static ProtoData getProtoData() {
    String str = Prefs.getString(Constants.SHARED_PREF_PROTO_DATA, null);
    ProtoData data = null;

    try {
        data = ProtoData.parseFrom(ByteString.copyFromUtf8(str));
    } catch (InvalidProtocolBufferException e) {
        e.printStackTrace();
    }

    return data;
}

      

+3


source to share


1 answer


You can store a byte array in SharedPreferences using android.util.Base64.

To save:

String saveThis = Base64.encodeToString(array, Base64.DEFAULT);

      



For loading:

byte[] array = Base64.decode(stringFromSharedPrefs, Base64.DEFAULT);

      

+3


source







All Articles