martin-stone / hsv-alpha-color-picker-android

A color picker and a color preference for use in Android applications.
Apache License 2.0
290 stars 60 forks source link

getColor() doesn't always return latest value #42

Closed zeevox closed 6 years ago

zeevox commented 6 years ago

I've been battling this problem I've been having and it seemed to me that something was wrong in my code, but according to the debugger it appears to be within this library.

I am using the latest version of this library (v2.3.0) and I have tried different targetSdk, compileSdk and Support Library revisions to no avail.

I have a ColorPreference on which I am calling setOnPreferenceChangeListener, and within that code I call...

Integer gradientEndColorValue = ((ColorPreference) findPreference("gradient_end_color")).getColor();

...so that I can then compare the value of gradientEndColorValue to another Integer color value.

But, according to the debugger, when I press "OK" on the dialog, the onPreferenceChangeListener is called, but getColor() returns the previous value, since SharedPreferences [hasn't written the new value to the store yet](https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()) since SharedPreferences.Editor.apply() is asynchronous.

I believe this library reads from SharedPreferences when calling getColor() in the following lines of code: ColorPreference.java#L119-L123

Would it be possible to store the current value in a variable so that getColor() returns the latest latest value, something like Android's ListPreference?

If you would like any debugger information, then I am happy to share it. Thank you!

martin-stone commented 6 years ago

According to the docs, your listener is called before the value is persisted (so that your listener can veto the saving). This is how the Android API is intended to work and not because of any asynchronous issue.

I think you just need to use the newValue parameter that's passed into your onPreferenceChange function. (Cast it to an Integer.)

zeevox commented 6 years ago

Thank you for your suggestion, it all works and this library is perfect! Next time I'll make sure to read the docs more carefully! :+1: