Вызвано: java.lang.IllegalArgumentException: не удалось сделать предположение для com.example.example.databinding.ContentClassApplicationMyClass1Binding

Я получаю эту ошибку в android после обновления студии android с 3.0 до 3.1 и Gradle с 3.1 до 4.4.

Как я могу это исправить?

Он правильно работает с Gradle 3.1 и android studio 3.0.

Как заставить его работать?

Приложение Gradle:

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'

    }
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'

repositories {

    mavenCentral()
    google()
    maven { url 'https://maven.fabric.io/public' }
}


android {
    compileSdkVersion 27

    dataBinding {
        enabled = true
    }

    defaultConfig {
        applicationId "com.example.example"
        minSdkVersion 22
        targetSdkVersion 23
        versionCode 13
        versionName "1.13"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true

        multiDexEnabled true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }




    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/ASL2.0'
    }


}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.0.2'

    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    implementation 'com.android.support:design:27.0.2'
    implementation 'com.google.firebase:firebase-messaging:11.8.0'
    implementation 'com.google.firebase:firebase-crash:11.8.0'
    implementation 'com.google.firebase:firebase-core:11.8.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.amazonaws:aws-android-sdk-cognitoidentityprovider:2.6.8'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.amazonaws:aws-android-sdk-core:2.6.8'
    compile 'com.amazonaws:aws-android-sdk-s3:2.6.8'
    compile 'com.amazonaws:aws-android-sdk-ddb:2.6.8'
    compile 'com.github.twinkle942910:monthyearpicker:0.0.1'
    compile('com.crashlytics.sdk.android:crashlytics:2.9.0@aar') {
        transitive = true;
    }
    compile 'com.google.android.gms:play-services-location:11.8.0'
    compile 'com.zsoltsafrany:needle:1.0.0'
    implementation 'com.android.support:cardview-v7:27.0.2'
    compile 'com.white:progressview:1.0.1'
    compile 'br.com.simplepass:loading-button-android:1.8.1'
    implementation files('/libs/android-sdk-0.1.0.jar')
    compile 'com.android.support:support-v4:27.0.2'

    compile 'com.clevertap.android:clevertap-android-sdk:3.1.8'


    compile 'testfairy:testfairy-android-sdk:1.+@aar'


    implementation 'com.github.bumptech.glide:glide:4.6.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}




apply plugin: 'com.google.gms.google-services'

Gradle-Project:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.31"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Gradle-wrapper.Properties:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip

Gradle.properties

org.gradle.jvmargs=-Xmx1536m
android.databinding.enableV2=true

Layout.xml

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

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:padding="4dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".Class_application_MyClass1"
        tools:showIn="@layout/activity_class_application_myclass_1">


        <ScrollView
            android:id="@+id/scrollView2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="60dip"
            android:layout_marginTop="20dip"
            android:padding="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">


            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:cardUseCompatPadding="true">

                <LinearLayout

                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:focusableInTouchMode="true"
                    android:orientation="vertical"
                    android:padding="25dp">


                    <android.support.design.widget.TextInputLayout

                        android:id="@+id/name_TextInputLayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="25dp">

                        <android.support.design.widget.TextInputEditText
                            android:id="@+id/name"
                            android:layout_width="match_parent"

                            android:layout_height="wrap_content"
                            android:drawablePadding="10dp"
                            android:hint="Name"
                            android:imeOptions="actionNext"
                            android:singleLine="true"
                            android:text=""
                            android:textSize="13sp" />

                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout

                        android:id="@+id/number_TextInputLayout"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="25dp">

                        <android.support.design.widget.TextInputEditText
                            android:id="@+id/number"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:drawablePadding="10dp"
                            android:hint="number"
                            android:inputType="textCapCharacters"
                            android:maxLength="10"
                            android:text=""
                            android:textAllCaps="true"
                            android:textSize="13sp" />

                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout

                        android:id="@+id/classnumber_TextInputLayout"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="25dp">

                        <android.support.design.widget.TextInputEditText
                            android:id="@+id/class_number"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:drawablePadding="10dp"
                            android:hint="class"
                            android:imeOptions="actionNext"
                            android:inputType="textCapCharacters"
                            android:maxLength="15"
                            android:singleLine="true"
                            android:text=""
                            android:textSize="12sp" />
                    </android.support.design.widget.TextInputLayout>


                </LinearLayout>

            </android.support.v7.widget.CardView>

        </ScrollView>


    </android.support.constraint.ConstraintLayout>
</layout>

Activity.xml

<?xml version="1.0" encoding="utf-8"?>

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/top_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".Class_application_MyClass1">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/fundscorner_blue"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

            <android.support.constraint.ConstraintLayout
                android:id="@+id/linearLayout3"
                android:layout_width="fill_parent"
                android:layout_height="20dp"
                android:background="@color/white"
                app:layout_anchor="@+id/content_class_application_myclass_1"
                app:layout_anchorGravity="top|center">

                <com.white.progressview.HorizontalProgressView
                    android:id="@+id/progress100"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="10dp"
                    android:progress="25"
                    app:progressReachColor="@color/colorPrimary"
                    app:progressTextColor="@color/colorPrimary"
                    app:progressTextVisible="false"
                    android:minHeight="20dip"
                    android:maxHeight="20dip"

                    />
            </android.support.constraint.ConstraintLayout>

        </android.support.design.widget.AppBarLayout>


        <include
            android:id="@+id/content_class_application_myclass_1"
            layout="@layout/content_class_application_myclass_1"/>

        <LinearLayout
            app:layout_anchor="@+id/content_class_application_myclass_1"
            app:layout_anchorGravity="bottom|center"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <Button
                android:background="@drawable/ripple"
                style="?borderlessButtonStyle"
                android:id="@+id/button_stage1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/fundscorner_blue"
                android:text="Next"
                android:textColor="@color/white"
                />

        </LinearLayout>


    </android.support.design.widget.CoordinatorLayout>
</layout>

В файле JAVA:

    ActivityClassApplicationMyClass1Binding binding;

        binding = DataBindingUtil.setContentView(this, R.layout.activity_class_application_myclass_1);



binding.name.settext("Name");

person jason    schedule 28.03.2018    source источник
comment
поделиться файлом Gradle   -  person Abhinav Gupta    schedule 28.03.2018
comment
Gradle from 3.1 to 4.4. что это значит?   -  person Santanu Sur    schedule 28.03.2018
comment
а также, если вы используете 27.1.0, измените его на 27.0.2, потому что у 27.1.0 есть ошибки !!   -  person Santanu Sur    schedule 28.03.2018
comment
Я использую сам 27.0.2.   -  person jason    schedule 28.03.2018
comment
Я добавил файлы градиента   -  person jason    schedule 28.03.2018
comment
@AbhinavGupta Я добавил файлы. Пожалуйста, проверьте это.   -  person jason    schedule 28.03.2018
comment
У тебя есть этот класс? ContentClassApplicationMyClass1Binding внутри папки databinding?   -  person Santanu Sur    schedule 28.03.2018
comment
@jason измените targetSdkVersion с 23 на 27   -  person Abhinav Gupta    schedule 28.03.2018
comment
@AbhinavGupta Я получаю ту же ошибку при попытке targetSdkVersion 27   -  person jason    schedule 28.03.2018
comment
@SantanuSur У меня нет папки с именем databinding. Это идентификатор, присвоенный макету внутри Activity.xml.   -  person jason    schedule 28.03.2018
comment
Можете ли вы опубликовать макет и уверены ли вы, что это единственное место, которое вы используете ContentClassApplicationMyClass1Binding   -  person Santanu Sur    schedule 28.03.2018
comment
@SantanuSur 2 других макета имели этот идентификатор. Спасибо за это . Но даже после удаления я получаю ту же ошибку!   -  person jason    schedule 28.03.2018
comment
Я тоже сталкиваюсь с подобной проблемой, поэтому это может помочь вам stackoverflow.com/questions/49422477/   -  person Rajasekaran M    schedule 07.04.2018
comment
Я также столкнулся с этой проблемой, поэтому проверьте это   -  person Rajasekaran M    schedule 07.04.2018
comment
@RajasekaranM Не сработало :( Кстати, этот код отлично работает с плагином Gradle 3.1, но когда я обновляюсь до плагина Gradle 4.4, он не работает.   -  person jason    schedule 08.04.2018


Ответы (5)


Это из-за вашего имени класса или имени пакета, которые используют привязку данных. Эти классы (которые используют привязку данных) должны начинаться с заглавной буквы, а пакеты - со строчной буквы.

person Mehdi Shojaeian    schedule 05.04.2018
comment
пакеты [должны] начинаться с нижнего регистра - это изменение по сравнению с предыдущим поведением, но теперь это действительно так - person Gabor; 04.07.2018
comment
Это сработало, я не понимаю, зачем они так делают! - person Kwnstantinos Nikoloutsos; 19.04.2019
comment
Это работает, но, к сожалению, это ломает / удаляет виджеты. Кто-нибудь знает способ обойти это? - person einUsername; 03.11.2020

Причиной этой ошибки является, как уже сказал Мехди в своем ответе, использование заглавных букв в имени пакета Java для классов привязки и переменных.

При дальнейшем изучении журналов вы можете увидеть, что ошибка возникает по адресу ClassName.bestGuess (String). Причина в том, что имя пакета ваших связанных классов, также как и те, которые указаны в поле <variable> в вашем макете, содержат символы верхнего регистра в имени своего пакета. Это приводит к тому, что метод не может отделить имя класса от имени пакета, и выдает ошибку.
[если честно, это довольно плохое поведение, но, вероятно, лучшего способа не существует (пока) ]

То же самое верно и для сгенерированного класса привязки, он также должен быть в пакете, в котором нет прописных букв. Поскольку по умолчанию используется имя пакета вашего приложения, вам необходимо изменить имя пакета java, добавив свойство class в поле <data> в макете (Подробнее здесь).

Пример:

<layout xmlns:app="http://schemas.android.com/apk/res-auto">
    <data class="com.example.ExampleDataBinding">
        <variable
            name="example"
            type="com.example.ExampleClass" />
    </data>
</layout>
person Maxr1998    schedule 01.05.2018
comment
Это отличное решение. Не забывайте и о applicationId в градиенте - person Sagar Patel; 24.05.2019
comment
ApplicationId менять не обязательно. Я думаю, это может вызвать проблемы, если приложение уже есть в магазине. - person einUsername; 03.11.2020

Имя класса привязки кажется неправильным. Можете попробовать сменить его с ActivityClassApplicationMyClass1Binding на ActivityClassApplicationMyclass1Binding

person Pavan    schedule 04.04.2018
comment
Я редактировал его, но дело в том, что тот же проект работает, если я не обновляю плагин gradle с 3.1 до 4.4. - person jason; 08.04.2018

вам нужно начинать все имя класса с заглавной буквы, а пакет - с маленькой.

person Suraj Gaur    schedule 03.04.2020

Как предлагали другие, имена пакетов должны начинаться с строчной буквы. Моя проблема заключалась в том, что он начинался с подчеркивания _, что тоже было недопустимо.

person Jan Málek    schedule 25.10.2019