天道酬勤,学无止境

Android in Kotlin: Error in Databinding from the project by Google codelabs

I was doing this course offered by Google, https://codelabs.developers.google.com/codelabs/kotlin-android-training-data-binding-basics/index.html?index=..%2F..android-kotlin-fundamentals#2,

The particular code in github: https://github.com/google-developer-training/android-kotlin-fundamentals-apps/tree/master/AboutMeDataBinding

Here I was doing the data binding, which is shown step by step how to implement it. But at the end I was getting an error with ActivityMainBinding

I have downloaded their solution code from github which on opening with Android-studio 3.4.1 , I got the same problem.

In Main Acctivity.kt

  package com.example.android.aboutme
    import android.content.Context
     import android.os.Bundle
     import android.view.View
   import android.view.inputmethod.InputMethodManager
  import androidx.appcompat.app.AppCompatActivity 
   import androidx.databinding.DataBindingUtil
   import com.example.android.aboutme.databinding.ActivityMainBinding

 class MainActivity : AppCompatActivity() {

private lateinit var binding: ActivityMainBinding

private val myName: MyName = MyName("Aleks Haecky")

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = DataBindingUtil.setContentView(this, 
R.layout.activity_main)

    binding.myName = myName

    binding.doneButton.setOnClickListener {
        addNickname(it)
    }

}


 private fun addNickname(view: View) {
    binding. apply {
        myName?.nickname = nicknameEdit.text.toString()
        invalidateAll()
        nicknameEdit.visibility = View.GONE
        doneButton.visibility = View.GONE
        nicknameText.visibility = View.VISIBLE
    }

    // Hide the keyboard.
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}

Build.gradle(module:app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.android.aboutme"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.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 "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    testImplementation 'junit:junit:4.12'
}

I expected to be all okay but ActivityMainBinding was red in colour. Error says unresolved reference.

IDE Fatal Error:
java.lang.NullPointerException
    at com.intellij.build.MultipleBuildsView.lambda$onEvent$2(MultipleBuildsView.java:218)
    at com.intellij.build.MultipleBuildsView.lambda$onEvent$4(MultipleBuildsView.java:310)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:435)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:419)
    at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:403)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:762)
    at java.awt.EventQueue.access$500(EventQueue.java:98)
    at java.awt.EventQueue$3.run(EventQueue.java:715)
    at java.awt.EventQueue$3.run(EventQueue.java:709)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:732)
    at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:755)
    at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:704)
    at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:391)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Unresolved reference: ActivityMainBinding
Unresolved reference: ActivityMainBinding
Unresolved reference: it
Unresolved reference: nicknameEdit
Unresolved reference: invalidateAll
Unresolved reference: nicknameEdit
Unresolved reference: doneButton
Unresolved reference: nicknameText

评论

I got this answer by a trial method. We need to simply, Clean the project followed by Rebuilding. For this to be done, we can simply omit(or delete) the imports which are depicted in grey (i.e. they are unnecessary in the project). Then, Build->Clean Project and after that Build->Rebuild Project.

Including the answer of @Chandramauli Chakraborty I also think you might have another error in your code or somewhere in any Kotlin or XML file. PLease make sure you have correctly fixed all of them,and them try to do what the college says.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Android - DataBinding - 如何以及何时生成绑定类?(Android - DataBinding - How and when the Binding classes will be generated?)
    问题 数据绑定指南状态 By default, a Binding class will be generated based on the name of the layout file, converting it to Pascal case and suffixing “Binding” to it. The above layout file was activity_main.xml so the generate class was ActivityMainBinding. 什么时候会生成 Binding 类,这里说 ActivityMainBinding。 我有编译时错误。 “无法解析 ActivityMainBinding”。 ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity); 任何帮助表示赞赏。 谢谢 回答1 你的布局名称是什么? 上面的布局文件是activity_main.xml,所以生成类是ActivityMainBinding。 这意味着生成的类名将取决于您的布局名称 activity_main.xml -> ActivityMainBinding.java 我认为您的活动名称是“main_activity”
  • 如何在Android Studio 3.0.0中使用数据绑定和Kotlin(How to use Data Binding and Kotlin in Android Studio 3.0.0)
    问题 我刚开始使用Android Studio 3.0.0,但是每次尝试构建项目时,都会出现此错误: Error:Circular dependency between the following tasks: :app:compileDebugKotlin +--- :app:dataBindingExportBuildInfoDebug | \--- :app:compileDebugKotlin (*) \--- :app:kaptDebugKotlin \--- :app:dataBindingExportBuildInfoDebug (*) (*) - details omitted (listed previously) 我在用 kapt "com.android.databinding:compiler:2.2.0" 在我使用之前 androidProcessor "com.android.databinding:compiler:2.2.0" 而且工作正常……我做错了什么?? 谢谢! 回答1 似乎您需要在模块级别的app .gradle中有3个gradle条目来添加数据绑定 apply plugin: 'kotlin-kapt' android { ... dataBinding { enabled = true } } dependencies {
  • Issue with data binding with gradle 3.2.1
    When i have updated android studios 3.2.0 to 3.2.1. I have use data binding, when run project show me error like this, if i am wrong please suggest me. Could not find com.android.databinding:compiler:3.2.1. Searched in the following locations: file:/C:/Users/Taufiq/AppData/Local/Android/Sdk/extras/m2repository/com/android/databinding/compiler/3.2.1/compiler-3.2.1.pom file:/C:/Users/Taufiq/AppData/Local/Android/Sdk/extras/m2repository/com/android/databinding/compiler/3.2.1/compiler-3.2.1.jar file:/C:/Users/Taufiq/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/databinding
  • Android Studio can't find Kotlin dependency
    I was trying to upgrade some dependencies for my Android Studio project and now I'm stuck with this error message whenever I try to build the project: Could not determine the dependencies of task ':app:compileDebugJavaWithJavac'. > Could not resolve all task dependencies for configuration ':app:debugAnnotationProcessorClasspath'. > Could not find org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.60-eap-25. Searched in the following locations: - https://dl.google.com/dl/android/maven2/org/jetbrains/kotlin/kotlin-stdlib-jdk8/1.3.60-eap-25/kotlin-stdlib-jdk8-1.3.60-eap-25.pom - https://jcenter.bintray
  • Jetpack Compose 学习资源汇总
    Jetpack Compose 为Android带来了先进的声明式UI开发方式。 近期alpha1.0正式发布,说明目前整体功能已接近完善,API也足够稳定,是时候开始学习一波了。 推荐一个项目,这里整理了各种高质量的官方、民间的Compose学习资料,有兴趣的同学不妨关注一下: ➡️ Learn Jetpack Compose Android ⬅️ aims to be your starting point to find the finest learning content for Jetpack Compose suites of libraries. Contents · Slides: 大会演讲、分享 · Official: 官方文档、代码实例 · Articles: 技术博客、文章 · Githubs: 民间开源项目 Slides https://speakerdeck.com/vinaygaba/360-andev-2020-learning-jetpack-compose-by-example [July 23, 2020] 360 | AnDev 2020:通过例子学习Jetpack Compose — Vinay Gaba https://speakerdeck.com/alexzhukovich/lets-build-an-android-ui-with
  • 使用 Kotlin for Android 进行数据绑定的问题(Issue with databinding using Kotlin for Android)
    问题 我正在尝试使用 Kotlin 为我的 Android 项目启用数据绑定。 我启用了 Kotlin 插件,但我无法启用数据绑定我不断收到以下错误 Error:(66, 0) Could not find method kapt() for arguments [com.android.databinding:compiler:2.0.0-beta6] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler 我的 gradle 文件中有以下数据绑定依赖项 dependencies { ... kapt 'com.android.databinding:compiler:2.0.0-beta6' } kapt { generateStubs = true } 回答1 编辑:使用 Kotlin 1.1 和 Kapt3,它的工作原理略有不同: 在您的项目build.gradle : buildscript { ext { ... plugin_version = "2.3.1" kotlin_version = "1.1.2-3" ... } ... dependencies { classpath "org.jetbrains.kotlin:kotlin
  • Cannot access activity binding android
    I have a layout file called activity_suggestions. I am using databinding in it. Hence the file ActivitySuggestionsBinding got generated. The project compiles successfully. But when I try to run the project, I get this error e: error: cannot access ActivitySuggestionsBinding I am using android studio 3.1.2 with kotlin version 1.4.1. Any help will be appreciated Edit Pasting my module level build.gradle and app level build.gradle Module Build.gradle apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' android { dataBinding { enabled = true } .. } dependencies{ .. compile "org.jetbrains
  • Cannot find symbol DataBindingComponent on Android Studio 3.2 Canary 16 Kotlin project
    I just created a new project on Android Studio 3.2 Canary 16 with Kotlin enabled. Then I also enabled data binding, but I'm getting an error saying that it could not find the DataBindingComponent class. Here's my project gradle: // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.2.41' ext.android_plugin_version = '3.2.0-alpha10' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.0-alpha16' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" //
  • Kotlin-DataBinding-Error: Check your module classpath for missing or conflicting dependencies
    How can I solve this problem. I can't make this data binding work, I have tried everything. Build.gradle(module app) apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' android { compileSdkVersion 27 defaultConfig { applicationId "com.fusion.alen.ask" minSdkVersion 16 targetSdkVersion 27 multiDexEnabled true versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" vectorDrawables.useSupportLibrary = true } androidExtensions { experimental = true }
  • Android Studio Canary 3.4 Canary 4 : ERROR: variant.getApplicationId() is not supported by feature plugins
    Since I updated my project on the new Android Studio 3.4 Canary 4, the gradle sync failed because: ERROR: variant.getApplicationId() is not supported by feature plugins as it cannot handle delayed setting of the application ID. Please use getApplicationIdTextResource() instead. Affected Modules: base I was previously on Canary 3 and it worked perfectly. The project is a multi feature app including an instant-app. Gradle version is gradle-5.0-milestone-1-all My project level build.gradle buildscript { ext.kotlin_version = '1.3.10' repositories { google() jcenter() } dependencies { classpath
  • AndroidX incompatible with DataBinding Android
    Ok, I've been tasked with migrating a project to AndroidX to reduce the clutter of the support libs in our project. I've enabled AndroidX as per the official docs but now I'm getting run time errors when trying to inflate views via the corresponding auto generated Binding classes that are created from enabling databinding in the modules gradle. Digging into the autogenerated source I came across this method, which is the one which is causing the code to throw: public List<DataBinderMapper> collectDependencies() { ArrayList<DataBinderMapper> result = new ArrayList(1); result.add(new com.android
  • Android 开发者学习路线(2020 版本)
    原文: https://www.androidperformance.com/2020/02/03/android-development-learning-path-2020-edition/#Android-Jetpack 仅作为个人学习目标。 目录 Programming Java Kotlin Flutter Android Studio Android Studio IDE Overview Project Structure — Java/Kotlin/Flutter, XML, .gradle files Android 基础知识 四大组件 Intents Static User Interface Dynamic User Interface CustomView UI Resources Fragments Support User Interface Storage Build Threading Debugging Memory Leak 3rd Party Library Data Format Android Jetpack Architecture Unit Testing Firebase Security App Release Programming Java Java 是 Android App 开发默认的语言, Android
  • Google宣布新的SDK版本控制系统后,Gradle项目同步失败(Gradle project sync failing after Google announced the new sdk versioning system)
    问题 我收到以下错误: Cannot change dependencies of configuration ':app:api' after it has been included in dependency resolution. 更新:禁用数据绑定后,我可以使用com.google.gms:google-services:3.3.0进行构建,但是对于需要启用数据绑定的用户而言,这不是解决方案。 Google宣布新的sdk版本控制系统(链接)后,我执行了以下步骤: 我按照指示更新了gradle文件,以分别包含gms和firebase版本号。 更新了apply plugin行,更新了classpath。 我仍然收到错误,并且不知道原因。 以下是相关的gradle文件: build.gradle(主要): buildscript { repositories { google() jcenter() maven { url 'https://dl.bintray.com/rvalerio/maven' } maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'com.android.tools.build:gradle:3.1.2' classpath 'com.google.gms
  • Kotlin-android:未解析的参考数据绑定(Kotlin-android: unresolved reference databinding)
    问题 我有以下使用新的数据绑定库用Java编写的片段类 import com.example.app.databinding.FragmentDataBdinding; public class DataFragment extends Fragment { @Nullable private FragmentDataBinding mBinding; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data, container, false); return mBinding.getRoot(); } } 它可以编译并运行良好。 我试图用Kotlin重写它,并提出了以下内容: import com.example.app.databinding.FragmentDataBdinding class ProfileFragment : Fragment() { private var mBinding: FragmentDataBinding? = null
  • com.android.tools.r8.errors.CompilationError: Program type already present: androidx.annotation.AnimRes
    I'm trying to rebuild my project which I've written in kotlin but it has constantly failed with the error Program type already present: androidx.annotation.AnimRes I've tried Invalidating cache cleaning and rebuilding using ./gradlew build --stacktrace --info command but without success. Exception is org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithMultidexlistForDebug' Stack trace is Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: Error while generating the main dex list. at com.android.builder.profile
  • 在Android数据绑定中找不到符号BR(cannot find symbol BR in android data binding)
    问题 我想使用Android数据绑定,并且已经根据官方文档进行了配置。 错误消息是:错误:找不到符号导入net.juude.droidviews.BR; 顶级build.gradle文件是: buildscript { repositories { jcenter() } dependencies { classpath "com.android.tools.build:gradle:1.3.0-beta2" classpath 'me.tatarka:gradle-retrolambda:3.0.1' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' classpath "com.android.databinding:dataBinder:1.0-rc0" } } allprojects { repositories { jcenter() mavenCentral() } } 并且app模块中的build.gradle文件是 apply plugin: 'com.android.application' apply plugin: 'me.tatarka.retrolambda' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'com
  • Android Support plugin errors after upgrading Android Studio to 3.1.0
    I use Kotlin and databinding for my project, after recent upgrade to Android Studio 3.1.0 I constantly see a lot of exceptions in Android Support plugin: Could not initialize class android.databinding.tool.ext.ExtKt java.lang.NoClassDefFoundError: Could not initialize class android.databinding.tool.ext.ExtKt at android.databinding.tool.reflection.ModelClass.getTypeName(ModelClass.java:688) at android.databinding.tool.reflection.ModelClass.equals(ModelClass.java:694) at android.databinding.tool.reflection.ModelClass.findSetter(ModelClass.java:614) at android.databinding.tool.reflection
  • savedInstanceState is null after first app shutdown but not after second
    I am following this codelab Android Kotlin Fundamentals 04.2: Complex lifecycle situations https://codelabs.developers.google.com/codelabs/kotlin-android-training-complex-lifecycle/index.html#4 In tast 5 you simulate app shutdown and use onSaveInstanceState() When I follow the instructions, but also when I run the solution code, saveInstanceState is not restored after the first app shutdown, but only after the second app shutdown. The solution code from Codelab: https://github.com/google-developer-training/android-kotlin-fundamentals-apps/tree/master/DessertClickerFinal And the MainActivity
  • Error :“Configuration 'compile' is obsolete and has been replaced with 'implementation'.”, even though no 'compile' present in gradle
    I have the following gradle files and I can't find anything which would still warrant the warning "Configuration 'compile' is obsolete and has been replaced with 'implementation'." First Module Gradle file: buildscript { repositories { maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'io.fabric.tools:gradle:1.24.1' } } repositories { maven { url 'https://maven.fabric.io/public' } } apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'io.fabric' apply plugin: 'kotlin-kapt' def
  • Execution failed for task ':app:kaptDebugKotlin'. when clean build
    I have problem about build project with cmd. When I build project with android studio is OK but when I clean project then build with cmd has error This command: gradlew assembleDebug This error: FAILURE: Build failed with an exception. *What went wrong: Execution failed for task ':app:kaptDebugKotlin'. Internal compiler error. See log for more details e: java.util.ServiceConfigurationError: javax.annotation.processing.Processor: android.databinding.annotationprocessor.ProcessDataBinding Unable to get public no-arg constructor at java.base/java.util.ServiceLoader.fail(ServiceLoader.java:581) at