Store ProtoBuf object in SharedPreferences

Viewed 485

I am meaning to store a ProtoBuf object in SharedPreferences. Protocol Buffers only allow parsing from ByteString or Byte Array. But SharedPreferences support neither. I was wondering if there was a way to do it without having to create another serializable model and mapping to it first.

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;
}
1 Answers
Related