Reputation: 2004
I am fetching a web service of a profile in which I am obtaining gender as 1- Male 2- Female and 3- Not Preferred(Referenced). The web service gives me the value of as 1, 2, 3.
And I am using 2-way data binding for setting up thing I had written a custom binding adapter that is throwing an error to me.
Here is Custom Binder Code
@BindingAdapter({"android:gender"})
public static String loadGender(Integer genderCode) {
if (genderCode == 1) {
return "Male";
} else if (genderCode == 2) {
return "Female";
} else if (genderCode == 3) {
return "Not Preferred";
}
return null;
}
and from xml I am accepting android:gender=@{userProfile.xxxx}
But I am not getting converted value
FAILURE: Build failed with an exception.
What went wrong: Execution failed for task ':app:compileDebugJavaWithJavac'.
android.databinding.tool.util.LoggedErrorException: Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'android:gender' with parameter type java.lang.String on android.support.design.widget.TextInputEditText. file:D:\AndroidProjects\HMA\hma_1.0_ankit\HMA-Android\HmaApplication\app\src\main\res\layout\fragment_profile_user.xml loc:136:42 - 136:67 ****\ data binding error ****
Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 1s 19 actionable tasks: 4 executed, 15 up-to-date
Can someone please let me know why I am wrong
Upvotes: 2
Views: 1546
Reputation: 779
You can't return a value from a Binding Adapter, you should rather do what you want inside of the Binding Adapter. Your method should be:
@BindingAdapter("android:gender")
public static void loadGender(TextInputEditText textInputEditText, int genderCode) {
String gender = null;
if (genderCode == 1) {
gender = "Male";
} else if (genderCode == 2) {
gender = "Female";
} else if (genderCode == 3) {
gender = "Not Preferred";
}
textInputEditText.setText(gender);
}
Data Binding will automatically pass in the TextInputEditText where you used your android:gender
attribute.
Also, you should use your attribute as follows:
android:gender="@{userProfile.xxxx}"
(Note quotation marks around @{})
Suggested improvement: Because you are not overriding a native Android attribute (android:gender
is not normally an attribute on views), I would recommend that you rather call your attribute "gender". Thus, you define your Binding Adapter with @BindingAdapter("gender")
and reference your attribute in XML as app:gender="@{userProfile.xxxx}"
Upvotes: 1