Не удается получить доступ к привязке активности Android - PullRequest
0 голосов
/ 07 мая 2018

У меня есть файл макета с именем activity_suggestions. Я использую привязку данных в нем. Следовательно файл ActivitySuggestionsBinding был сгенерирован. Проект успешно компилируется. Но когда я пытаюсь запустить проект, я получаю эту ошибку

e: error: cannot access ActivitySuggestionsBinding

Я использую Android Studio 3.1.2 с версией Kotlin 1.4.1. Любая помощь будет оценена

Редактировать
Вставка моего уровня модуля build.gradle и уровня приложения build.gradle

Модуль Build.gradle

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {

    dataBinding {
        enabled = true
    }
..
}

dependencies{
..
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "com.google.dagger:dagger:$rootProject.daggerVersion"
    implementation "com.google.dagger:dagger-android:$rootProject.daggerVersion"
    implementation "com.google.dagger:dagger-android-support:$rootProject.daggerVersion"
    kapt "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion"
    kapt "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
    provided 'javax.annotation:jsr250-api:1.0'
    implementation "android.arch.lifecycle:runtime:$rootProject.archVersion"
    implementation "android.arch.lifecycle:extensions:$rootProject.archVersion"
    annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archVersion"
    kapt "com.android.databinding:compiler:3.1.2"
..
}

Приложение build.gradle

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android{

    dataBinding{
        enabled = true
    }
..
}

dependencies{
    compile project(':module')
    kapt "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion"
    kapt "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
    kapt "com.android.databinding:compiler:3.1.2"
..
}

Это действие, к которому я обращаюсь ActivitySuggestionsBinding. Компилируется без ошибок.

class SuggestionsActivityScreen : BaseActivity() {

    var binding : ActivitySuggestionsBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_suggestions)
        binding?.model = SuggestionActivityViewModel()

    }
}

При компиляции базового модуля (приложения) я получаю ошибку

 error: cannot access ActivitySuggestionsBinding
  class file for com.dom.comp.databinding.ActivitySuggestionsBinding not found
  Consult the following stack trace for details.
  com.sun.tools.javac.code.Symbol$CompletionFailure: class file for com.dom.comp.databinding.ActivitySuggestionsBinding not found

Это моя активность_suggestions.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:card_view="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="model"
            type="com.dom.domp.SuggestionActivityViewModel"/>
    </data>

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:focusableInTouchMode="true"
    android:padding="@dimen/step1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@{model.namedString}"/>
</RelativeLayout>
</layout>

И я попытался очистить, сделать недействительным кеш Это не решает проблему.

Ответы [ 3 ]

0 голосов
/ 16 мая 2018

Добавить в вас следующее app build.gradle

kapt "com.android.databinding:compiler:$android_plugin_version"
apply plugin: 'kotlin-kapt' // This one at top where plugin belong to

Это поможет.

$android_plugin_version - версия com.android.tools.build:gradle в application build.gradle

Также добавьте это в свой модуль build.gradle

android { /// Existing Code kapt { generateStubs = true } }

0 голосов
/ 14 июля 2018

У меня была похожая проблема. Я получаю ошибку

error: cannot access RepeatPaymentFragmentBinding
class file for RepeatPaymentFragmentBinding not found
Consult the following stack trace for details.
com.sun.tools.javac.code.Symbol$CompletionFailure: class file for my.package.databinding.RepeatPaymentFragmentBinding not found

Потратил пару дней, чтобы понять, что проблема не в GDB, а в Dagger2. Оказалось, что Dagger не поддерживает использование сгенерированных классов в генерируемом коде.

Итак, в моем модуле :library был такой класс:

class RepeatPaymentFragment: BaseFragment<RepeatPaymentFragmentBinding>() {
...
}

И компонент кинжала для него находился в модуле :app. Таким образом, два процессора аннотаций мешают друг другу.

После того, как я удалил дженерик из своих фрагментов, он прекрасно компилируется.

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

0 голосов
/ 16 мая 2018

В этой демонстрации это работает и попробуйте следующим образом ... добавьте только код включения привязки данных в файл gradle уровня приложения, как показано ниже:

dataBinding {
    enabled = true
}

код ниже - мой файл gradle уровня приложения ..

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
compileSdkVersion 27
defaultConfig {
    applicationId "com.example.adruser.rafdemo"
    minSdkVersion 23
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
dataBinding {
    enabled = true
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.google.android.gms:play-services-maps:11.6.0'
implementation 'com.google.android.gms:play-services-location:11.6.0'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.intuit.sdp:sdp-android:1.0.4'
implementation 'com.github.bumptech.glide:glide:4.7.1'


}
repositories {
mavenCentral()
}

затем после в файле gradle.properties уровня проекта добавьте строку ниже ...

android.databinding.enableV2=true

создайте файл user_layout.xml, как показано ниже:

<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
    <variable
        name="user"
        type="com.example.adruser.rafdemo.model.User"/>
</data>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dp">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text='@{user.name}'/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:id="@+id/ulTvName"
        android:text="@{user.dob}"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:id="@+id/ulTvAge"
        android:text="@{Integer.toString(user.age)}"
        app:layout_constraintTop_toBottomOf="@+id/ulTvName"
        />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:id="@+id/ulTvDob"
        android:text="@{user.dob ?? user.expDob}"
        app:layout_constraintTop_toBottomOf="@+id/ulTvAge"
        />
</android.support.constraint.ConstraintLayout>
</layout>

затем после создания класса pojo User.java, как показано ниже: вы можете также сделать класс pok *. 1013 *

public class User {
public String name,dob,expDob;
public int age;
public User(){}
public User(String name, String dob,String expDob, int age) {
    this.name = name;
    this.dob = dob;
    this.age = age;
    this.expDob=expDob;
}
public static String display(){
    return "rajesh";
}
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getDob() {
    return dob;
}

public void setDob(String dob) {
    this.dob = dob;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

}

, затем, наконец, создать класс DatabindingActivity.kt для привязки ..

class DatabindingActivity :AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    var binding:UserLayoutBinding=DataBindingUtil.setContentView(this,R.layout.user_layout)
    val user = User("karan", null, "25/06/1994", 24)
    binding.user=user
}
}
...