How I handled null values in Android Proto DataStore?
Jetpack DataStore is new data storage solution in Android that would replace SharedPreference in future. DataStore allows you to store key-value pairs or typed objects with protocol buffers.
If you’re currently using
SharedPreferences to store data, so it’s good time to start migration to DataStore instead.
DataStore provides two different implementations: Preferences DataStore and Proto DataStore.
I was very excited to know practically how this new storage solution (DataStore) works. So in the Christmas holidays, I made a sample project on Proto DataStore to learn and improve my skills.
While working with DataStore i had multiple issues, but the major and most challenging issue was supporting null values in Proto DataStore.
We can’t store null values in Proto DataStore instead we have other solutions.
I found following solutions to add Null support in proto3, you can use according to your use-case.
(I will add more solutions as soon as i will come to know)
We have wrappers.proto to support null in protobuffers
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…
To use above wrappers you need to import “google/protobuf/wrappers.proto”;
And to declare nullable string use StringValue,
We can use Oneof to define a nullable type, as of my understanding the best way of using this is 👇🏼
But in this case, you have to do a lot of additional stuff, like handling null via if else in service implementation.
Method 3 (using Default Values — Recommended)
In proto3 all fields are optional by default so each field have default value
These defaults are type-specific:
- For strings, the default value is the empty string.
- For bytes, the default value is empty bytes.
- For bools, the default value is false.
- For numeric types, the default value is zero.
- For enums, the default value is the first defined enum value, which must be 0.
- For message fields, the field is not set. Its exact value is language-dependent. See the generated code guide for details.
We have to handle these default values using conditional code like if object is null pass its default value instead.
That’s all from my learnings!!
Hey!!, I am ready to add more methods , if you know something different to handle null in protocol-buffers, Please let me know. i will be very thankful to you. you can find me on LinkedIn.