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