web-dev-qa-db-fra.com

Liaison de données bidirectionnelle dans EditText

J'ai cet objet 

ObservableInt someNumber;

public ObservableInt getSomeNumber()
{
    return someNumber;
}

public void setSomeNumber(ObservableInt number)
{
    this.someNumber = number;
}

et mon AppCompatEditText est comme ceci dans le code XML:

<Android.support.v7.widget.AppCompatEditText
        Android:layout_width="0dp"
        Android:layout_height="@dimen/agro_item_height"
        Android:layout_weight="1"
        Android:inputType="numberDecimal"
        Android:text="@={String.valueOf(myObject.someNumber)}"
        Android:gravity="center_horizontal"/>

J'ai cette erreur:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Java.lang.RuntimeException: failure, see logs for details.
cannot generate view binders Java.lang.NullPointerException
at Android.databinding.tool.expr.MethodCallExpr.generateCode(MethodCallExpr.Java:69)
at Android.databinding.tool.expr.Expr.toFullCode(Expr.Java:745)
at Android.databinding.tool.expr.Expr.assertIsInvertible(Expr.Java:767)
at Android.databinding.tool.BindingTarget.addInverseBinding(BindingTarget.Java:68)
at Android.databinding.tool.LayoutBinder.<init>(LayoutBinder.Java:228)
at Android.databinding.tool.DataBinder.<init>(DataBinder.Java:52)
at Android.databinding.tool.CompilerChef.ensureDataBinder(CompilerChef.Java:83)
at Android.databinding.tool.CompilerChef.sealModels(CompilerChef.Java:168)
at Android.databinding.annotationprocessor.ProcessExpressions.writeResourceBundle(ProcessExpressions.Java:149)
at Android.databinding.annotationprocessor.ProcessExpressions.onHandleStep(ProcessExpressions.Java:82)
at Android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.runStep(ProcessDataBinding.Java:154)
at Android.databinding.annotationprocessor.ProcessDataBinding$ProcessingStep.access$000(ProcessDataBinding.Java:139)
at Android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.Java:66)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.Java:794)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.Java:705)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.Java:91)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.Java:1035)
at com.Sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.Java:1176)
at com.Sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.Java:1170)
at com.Sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.Java:856)
at com.Sun.tools.javac.main.Main.compile(Main.Java:523)
at com.Sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.Java:129)
at com.Sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.Java:138)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.Java:46)
at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.Java:33)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.Java:104)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.Java:53)
at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.Java:38)
at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.Java:35)
at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.Java:25)
at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.Java:163)
at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.Java:145)
at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.Java:93)
at com.Android.build.gradle.tasks.factory.AndroidJavaCompile.compile(AndroidJavaCompile.Java:49)
at Sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at Sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.Java:62)
at Sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.Java:43)
at Java.lang.reflect.Method.invoke(Method.Java:498)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.Java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.Java:245)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.Java:221)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.Java:232)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.Java:210)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.Java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.Java:61)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.Java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.Java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.Java:66)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.Java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.Java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.Java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.Java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.Java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.Java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.Java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.Java:66)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.Java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.Java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.Java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.Java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.Java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.Java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.Java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.Java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.Java:153)
at org.gradle.internal.Factories$1.create(Factories.Java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:53)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.Java:150)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.Java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.Java:98)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.Java:92)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:91)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.Java:63)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.Java:92)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.Java:83)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.Java:99)
at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.Java:46)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.Java:35)
at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.Java:58)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.Java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.Java:48)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.Java:30)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.Java:81)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.Java:46)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.Java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.Java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.Java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.Java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.Java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.Java:72)
at org.gradle.util.Swapper.swap(Swapper.Java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.Java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.Java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.Java:60)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.Java:72)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.Java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.Java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.Java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.Java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.Java:237)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.Java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.Java:40)
at Java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.Java:1142)
at Java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.Java:617)
at Java.lang.Thread.run(Thread.Java:745)

J'ai déjà essayé juste avec 

Android:text="@={myObject.someNumber}"

mais j'ai cette erreur:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute     'Android:text' with value type int on Android.support.v7.widget.AppCompatEditText.
file:C:\Users\Moviit\AndroidStudioProjects\pbbchile-Android\app\src\main\res\layout\row_agro_tab.xml
loc:51:8 - 60:48
****\ data binding error ****

Quelqu'un a un exemple de comment faire cela?

6
Dan Ponce

Grâce aux adaptateurs de liaison de @LongRanger, j'ai pu avancer beaucoup plus dans ma solution, mais j'ai dû faire quelques modifications sur les adaptateurs et dans mon code. Tout d'abord, je devais initier le membre ObservableInt comme ceci:

ObservableInt someNumber;

public ObservableInt getSomeNumber()
{
    return someNumber;
}

public void setSomeNumber(ObservableInt number)
{
    this.someNumber = number;
}

Deuxièmement, je devais changer les adaptateurs donnés par @LongRanger pour ressembler à ceci:

@BindingAdapter("Android:text")
public static void bindIntegerInText(AppCompatEditText tv, int value)
{
    tv.setText(String.valueOf(value));    

    // Set the cursor to the end of the text
    tv.setSelection(tv.getText().length());
}

@InverseBindingAdapter(attribute = "Android:text")
public static int getIntegerFromBinding(TextView view)
{
    String string = view.getText().toString();

    return string.isEmpty() ? 0 : Integer.parseInt(string);
}

De cette façon, j’évite l’erreur: int "" non valide lorsque je tente de faire Integer.parse (...) sur @InverseBindingAdapter. Après cela, je devais placer le curseur à la fin de l'EditText avec le @BindingAdapter, sinon le curseur continuait à se déplacer au début.

1
Dan Ponce

Il existe une astuce non publiée pour les conversions primitives simples:

<Android.support.v7.widget.AppCompatEditText
    Android:layout_width="0dp"
    Android:layout_height="@dimen/agro_item_height"
    Android:layout_weight="1"
    Android:inputType="numberDecimal"
    Android:text="@={`` + myObject.someNumber}"
    Android:gravity="center_horizontal"/>

Je crois que cela n’a été ajouté que dans Android Studio 2.2.

9
George Mount

@CommonsWare a raison, vous devriez utiliser ObservableField<Str‌​ing> au lieu de ObservableInt. Si vous avez vraiment besoin de ce nombre, analysez-le simplement Integer.valueOf(stringNumber).

public ObservableField<Str‌​ing> someNumber;

//and in xml code:

<EditText
        Android:layout_width="0dp"
        Android:layout_height="@dimen/agro_item_height"
        Android:layout_weight="1"
        Android:inputType="numberDecimal"
        Android:text="@={myObject.someNumber}"
        Android:gravity="center_horizontal"/>

&EACUTE;DIT&EACUTE;: ou, comme mentionné, écrivez @InverseBindingAdapter personnalisé

public class MyEditTextBindingAdapters {

    @BindingConversion
    public static String intToStr(Integer value) {
        return value != null ? String.valueOf(value) : "";
    }

    @InverseBindingAdapter(attribute = "Android:text")
    public static Integer captureIntValue(EditText view) {
        long value = 0;
        try {
            value = Integer.parseInt(view.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return value;
    }
}
1
Roman_D

Vous pouvez faire une liaison bidirectionnelle sur EditText.

En utilisant la liaison de données unidirectionnelle, vous pouvez définir une valeur pour un attribut et définir un écouteur qui réagit à une modification de cet attribut

la variable est un type de chaîne

<Android.support.v7.widget.AppCompatEditText
    ...
    Android:text="@={model.someString}"
    />

la variable est le nombre

<Android.support.v7.widget.AppCompatEditText
    ...
    Android:text="@={`` + model.someNumber}"
    />

`` deux apostrophe arrière font la liaison automatiquement

  • convertir un nombre en chaîne lors de la définition sur EditText
  • convertir le texte de la chaîne en nombre lors de la définition dans le modèle

Pointe

Dans documentation vous pouvez voir que la liaison bidirectionnelle peut être utilisée à plusieurs fins. 

  1. CheckBox, RadioButton, Commutateur, ToggleButton 

Android:checked="@={model.checked}"

  1. RadioGroup - Android:checkedButton

Android:checkedButton="@={model.selectedId}"

  1. NoteBar - Android:rating 

Android:rating="@={model.rating}"

etc.

1
Khemraj

J'essaie d'utiliser le configurateur personnalisé comme @George Mount mentionné ( https://medium.com/google-developers/Android-data-binding-custom-setters-55a25a7aea47#.vsry4d95w ), et inspiré par cette réponse ( La liaison bidirectionnelle Android avec le type Integer entraîne l’absence de liaison de données

Vous pouvez toujours utiliser le code d'origine pour une liaison bidirectionnelle.

Classe de modèle

public class Age {
    private ObservableInt someNumber;
    private ObservableField<String> someStr;
    public Age() {
        someNumber = new ObservableInt();
        someStr = new ObservableField<>();
    }
    public ObservableInt getSomeNumber() {
        return someNumber;
    }
    public void setSomeNumber(ObservableInt pSomeNumber) {
        someNumber.set(pSomeNumber.get());
    }
    public ObservableField<String> getSomeStr() {
        return someStr;
    }
    public void setSomeStr(ObservableField<String> pSomeStr) {
        someStr.set(pSomeStr.get());
    }
}

Sélecteur et getter personnalisés pour l'attribut

@BindingAdapter("Android:text")
public static void bindIntegerInText(AppCompatEditText tv, int value) {
    tv.setText(String.valueOf(value));
}
@InverseBindingAdapter(attribute = "Android:text")
public static int getIntegerFromBinding(TextView view) {
    return Integer.parseInt(view.getText().toString());
}

Code en activité

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMain2Binding binding = DataBindingUtil.setContentView(this, R.layout.activity_main2);
    mAge = new Age();
    mAge.setSomeNumber(new ObservableInt(3));
    mAge.setSomeStr(new ObservableField<>("Test"));
    binding.setAge(mAge);
    binding.btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAge.setSomeNumber(new ObservableInt(4));
            mAge.setSomeStr(new ObservableField<>("Hello World"));
        }
    });
}

Je fais 4 démos avec ObservableInt, Observable, ressource String normale et ressource String de liaison dans le xml. 

<string name="helloworld">Hello World</string>

activity_main3.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:Android="http://schemas.Android.com/apk/res/Android"

    >

    <data>

        <variable
            name="age"
            type="example.com.testerapplication.Age"/>
    </data>

    <LinearLayout
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:orientation="vertical">

        <Android.support.v7.widget.AppCompatEditText
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="@={age.someNumber}"/>

        <Android.support.v7.widget.AppCompatEditText
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="@={age.someStr}"/>

        <Android.support.v7.widget.AppCompatEditText
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="@string/helloworld"/>

        <Android.support.v7.widget.AppCompatEditText
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="@{@string/helloworld}"/>

        <Button
            Android:id="@+id/btn"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:text="Test"
            />
    </LinearLayout>

</layout>
1
Long Ranger

Faites simplement ceci:

Android:text="@={user.username}"

Code complet:

 <EditText
            Android:id="@+id/username"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:hint="user name"
            Android:text="@={user.username}"/>

Et classe d'utilisateurs

public class User {
public ObservableField<String> username = new ObservableField<>();
public ObservableField<String> password = new ObservableField<>();

public User() {
    this("", "");
}

public User(String username, String password) {
    this.username.set(username);
    this.password.set(password);
}