I have a StringDef annotated interface
@StringDef({
SpecialString.A,
SpecialString.B
})
@Retention(RetentionPolicy.SOURCE)
public @interface SpecialString {
String B = "BBB";
String A = "AAA";
}
Which I use on a field in a parcelable object
public class MyParcelable implements Parcelable {
private final @SpecialString String mType;
protected MyParcelable (Parcel in) {
//Android studio shows an error for this line declaring
//"Must be one of SpecialString.A, SpecialString.B"
mType = in.readString();
}
...
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mType);
}
}
How can I handle parceling a String annotated by @StringDef
without resorting to suppressing with //noinspection WrongConstant
?
StringDef fields are supported by Parcelable but there is currently no way to ensure the value read back is one of the accepted values.
The method can be safely ignored in Android Studio by adding the comment noinspection WrongConstant
Safer alternatives may be to use an Enum and read it with MyEnum.valueOf(readString)
or as CommonsWare suggested, to write an int ordinal or constant instead of the String and do a lookup when the value is read.