Android Custom Setting Not Preserved

I am trying to get an existing Preference subclass for work that preserves the color value. I did not write a class, but it should work on android-7 and above (I am compiling target-android-9.) The full source code is here . Here, where the preference is kept:

@Override public void onColorChanged(int color) { if (isPersistent()) { boolean ret = persistInt(color); } // (update preview box, other stuff) } 

Using the debug output, I can say that isPersistent() returns true , but persistInt() returns false . According to the documentation for Android , persistInt() returns whether the preference is constant; how can they return different values? (Note: setPersistent(true) explicitly called from the constructor.)

In any case, the value is not saved. The call getPersistedInt(defaultValue) returns the default value, even later in the same instance of the class. In the code below, getPersistedInt() always called and always returns mDefaultValue .

 public int getValue() { try { if (isPersistent()) { mValue = getPersistedInt(mDefaultValue); } } catch (ClassCastException e) { mValue = mDefaultValue; } return mValue; } 

Why is this and how can I make sure that preference is maintained?

+6
source share
1 answer

After much hopeless searching, I finally found a problem: no key was assigned to the preference value due to a simple typo in the XML file of my preferences. (I used android.key instead of android:key .)

Since Android does not warn you when you try to save a preference that does not have a key (but it doesnโ€™t work instead), you should call the shouldPersist() function instead of isPersistent() before trying to save the value, and possibly a warning log if shouldPersist() returns false. For instance:

 @Override public void onColorChanged(int color) { mValue = color; if (shouldPersist()) { persistInt(color); } else { if (isPersistent()) Log.w("myapp", "shouldPersist() returned false. Check if this preference has a key."); } // (update preview box, other stuff) } 
+8
source

Source: https://habr.com/ru/post/890554/


All Articles