Search code examples
androidandroid-viewmodeltwo-way-binding

Two-way data binding Converter


I'm trying to use a converter from CharArray to String for my password two-way databinding field.

var password = ObservableField<CharArray>()

Following the doc :

public class Converter {
    @InverseMethod("stringToCharArray")
    public static String charArrayToString(
            ClearableEditText view,
            char[] oldValue,
            char[] value
    ){
        return value.toString();
    }

    public static char [] stringToCharArray(
            ClearableEditText view,
            String oldValue,
            String value
    ){
        return value.toCharArray();
    }
}

In XML file I used it like this :

android:text="@={Converter.charArrayToString(viewModel.password)}"

But I still got the bellow exception :

error: Could not find inverse method: public static char[] stringToCharArray(ClearableEditText, char[], java.lang.String)
    public static String charArrayToString(
                         ^   

Solution

  • This work fine for me, maybe after restarting AS :

    public class Converter {
        @InverseMethod("toCharArray")
        public static String toString(char [] value) {
            if(value == null) return "";
            return value.length == 0 ? "" : String.valueOf(value);
        }
    
        public static char [] toCharArray(String value) {
            if(value == null) return "".toCharArray();
            return value.isEmpty() ? "".toCharArray() : value.toCharArray();
        }
    }