skydoves / PreferenceRoom

:truck: Android processing library for managing SharedPreferences persistence efficiently and structurally.
Apache License 2.0
378 stars 26 forks source link

How to create an entry in preference room, with default value #24

Closed Dalakoti07 closed 3 years ago

Dalakoti07 commented 3 years ago

Describe the Bug: How to create entry in room preference component with some default value, as of I am doing it like below

@PreferenceEntity("OnBoardingData") open class OnBoardingData { @KeyName("fake") @JvmField val fakeBoolean = true }

Here I have to make sure that annotation name and variable name are different like "fake" and fakeBoolean, now I check if preference entry is null then get default value, something like this

if(onBoardingComponent.OnBoardingData.cntainsFake()){ .......... }else{ // use default value like onBoardingComponent.OnBoardingData.fakeBoolean }

Expected Behavior: Is their not a way to add this default value into the prefs, rather than making an extra check while consuming it

skydoves commented 3 years ago

Hi, you should use fake property instead of the fakeBoolean method. Because OnBoardingData class will be generated on the compile-time, and getFake method will be generated like the below. The @KeyName annotation will change and generate getFake() method instead of the getGakeBoolean() method.


component.OnBoardingData().fake // default value is true.

@Nullable
  public boolean getFake() {
    return preference.getBoolean("fake", true);
  }
Dalakoti07 commented 3 years ago

Thank you for prompt reply, but how to achieve this when field is custom object something like Car, in that case generated code has something like this

@Nullable public Cars[] getCars() { ......... return (Cars[])value.convertType(preference.getString("cars", null)); }

I want default array arraylist rather than null. Save arrayList as string with help of typeConvertors

skydoves commented 3 years ago

For the custom object, there is no way to set a default value now.

Dalakoti07 commented 3 years ago

Okay, thanks.

Are you planning to add this in coming versions?

skydoves commented 3 years ago

Not in the recent schedule, but I will consider it. Thanks for your report!

Dalakoti07 commented 3 years ago

Thanks