174

I have following fragment class written in Java using the new databinding library

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();
    }
}

It compiles and runs fine.
I tried to rewrite it in Kotlin and came up with the following:

import com.example.app.databinding.FragmentDataBdinding

class ProfileFragment : Fragment() {

    private var mBinding: FragmentDataBinding? = null

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data, container, false)
        return mBinding!!.getRoot()
    }
}

But now step :app:compileDebugKotlin outputs the following:

Error:(16, 38) Unresolved reference: databinding
Error:(37, 27) Unresolved reference: FragmentDataBinding

How can I use android-databinding library with Kotlin?

My top-level build.gradle:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0'
        classpath 'com.android.databinding:dataBinder:1.0-rc4'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

My build.gradle in app dir (only relevant parts):

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

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

buildscript {
    ext.kotlin_version = '0.14.451'
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}
repositories {
    mavenCentral()
    maven {
        url 'http://oss.sonatype.org/content/repositories/snapshots'
    }
}

I'm using Android Studio 1.4, Build tools version 23.0.1, Android SDK 23, SDK tools 24.4.0

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
Mikhail
  • 3,666
  • 4
  • 30
  • 43
  • 3
    Please, feel free to vote for the corresponding issue: [https://youtrack.jetbrains.com/issue/KT-8007](https://youtrack.jetbrains.com/issue/KT-8007) – Ghedeon Oct 16 '15 at 23:01
  • 1
    You only need to have `apply plugin: 'kotlin-kapt'` in app gradle file in most recent version. – Hesam Aug 04 '18 at 00:10
  • private lateinit var binding : FragmentDataBinding Is a better way of initializing – Dino Sunny Jun 15 '20 at 10:01

22 Answers22

96

Try use this configuration:

In main build.gradle:

buildscript {
    ext.kotlin_version = '<kotlin-version>'
    ext.android_plugin_version = '2.2.0-alpha4'
    dependencies {
        classpath "com.android.tools.build:gradle:$android_plugin_version"
    //... rest of the content
    }
}

App build.gradle:

android {
    dataBinding {
        enabled = true
    }
}

dependencies {
    kapt "com.android.databinding:compiler:$android_plugin_version"
}

kapt {
    generateStubs = true
}
Avinash R
  • 3,101
  • 1
  • 27
  • 47
lrampazzo
  • 1,219
  • 9
  • 7
  • 1
    @Irampazzo, `2.2.0-alphaX` is available, and FYI the version of data-binding is same as that of android-gradle-plugin itself. so you can externalize that version and use it as the compiler's version. – Avinash R Jul 01 '16 at 17:24
  • 1
    I can confirm that this answer fixed my issue with databinding and kotlin – Rabie Jradi Dec 16 '16 at 12:42
  • 12
    I had to add `apply plugin: 'kotlin-kapt'` also. See http://stackoverflow.com/a/42974558/1916449 – arekolek May 20 '17 at 18:20
  • I tried this. Now it gives me a circular dependency error. Any idea about this ? – leoOrion May 28 '17 at 09:19
  • Check out https://kotlinlang.org/docs/tutorials/android-frameworks.html#data-binding for official documentation on this. – Brian Aug 13 '17 at 16:13
  • correct one, and dont forget to add :) repositories { maven { url "https://maven.google.com" } } – Peter Aug 14 '17 at 20:13
  • I had tried the above and it only worked when restarting Android Studio. Worth trying if you're still not having any luck. – HBG Aug 20 '17 at 06:36
  • worked for me except my version is 3.0.0-beta2, be sure to set your version correctly, an sync gradle – Les Sep 01 '17 at 13:13
  • I had to add the following lines too: `plugins { id 'kotlin-android' id 'kotlin-android-extensions' } apply plugin: 'kotlin-kapt'` – Timothy Sawe Mar 28 '23 at 03:55
91

I found new solution, hope it will helps you.

First of all check whether plugin applied:

apply plugin: 'kotlin-kapt'

then

android {
    ...
    ...
    dataBinding {
        enabled = true
    }
    ...
    ...
}

You might have an error in dependency:

USE

kapt 'com.android.databinding:compiler:3.1.4'

instead of

compile 'com.android.databinding:compiler:3.1.4'

You can visit here for new version

Thank you.

And use layout tags in layout file before using its binding class , you can easily do that : In layout file your root view (e.g.- Constraint Layout) ALT+Enter -> convert to data binding class

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
20

In my case, this solved my problem.

I added this in the app build.gradle:

buildFeatures {
    dataBinding true
    viewBinding true 
}
Panayot
  • 484
  • 1
  • 6
  • 18
14

Update 2: This is a really old answer, instead refer to lrampazzo's answer.

It works with 1.0-rc4, put

kapt 'com.android.databinding:compiler:1.0-rc4' 

into your dependencies

Thanks Ghedeon, for the link in comments

Update: Here's a really simple hello world example project

Jaydeep Solanki
  • 2,895
  • 5
  • 36
  • 50
  • I still get the same error, am i doing something wrong here? https://gist.github.com/xdgimf/820c433efa8307821788 – Miguel Fermin Oct 29 '15 at 15:55
  • here's my build.gradle file if you need a reference https://gist.github.com/jaydeep17/9960fdb0e5a1ba85e82d – Jaydeep Solanki Oct 30 '15 at 03:33
  • @Jaydeep Have just tried it, and it's working. However Android studio doesn't highlight syntax and generates lots of IDE errors with message `Exception while analyzing expression at (12,23) in /projectpath/KotlinDataBinding/app/src/main/java/com/example/kotlindatabinding/MainActivity.kt:`. Do you have the same errors? And what's your android studio version? – Mikhail Nov 02 '15 at 13:06
  • @Arkadiy It's already been reported https://youtrack.jetbrains.com/issue/KT-8007 BTW I'm on studio v1.5 Preview 2 – Jaydeep Solanki Nov 03 '15 at 07:05
  • This is no longer the latest version of the plugin. It'll cause unnecessary pain. – Avinash R Jul 01 '16 at 19:15
  • It didn't work for me without the `kapt { generateStubs = true }` in there as well. Please update your answer. Also note of the latest comment by Avinash R: `1.0-rc4` is no longer the latest version of the plugin. – AplusKminus Oct 13 '16 at 14:14
  • I had to add apply plugin: 'kotlin-kapt' – Andrii Kovalchuk May 26 '17 at 21:21
  • Voted up for the direction mentioning this one as an 'Old answer'. Thoughtful and Helpful! – sud007 Dec 13 '19 at 09:44
13

The version of Data Binding compiler is same as gradle version in your project build.gradle file:

// at the top of file 
apply plugin: 'kotlin-kapt'


android {
  dataBinding.enabled = true
}

dependencies {
  kapt "com.android.databinding:compiler:3.0.0-beta1"
}

and the gradle version is

classpath 'com.android.tools.build:gradle:3.0.0-beta1'

Here is an example link to complete using of databinding library in kotlin.

https://proandroiddev.com/modern-android-development-with-kotlin-september-2017-part-1-f976483f7bd6

Mahamudul Hasan
  • 308
  • 3
  • 7
7

To Solve the problem, you have to put

apply plugin: 'kotlin-kapt'

at the top of build.gradle (Module: app), then put this line in dependencies

kapt "com.android.databinding:compiler:[YOUR_ANDROID_PLUGIN_VERSION]"

You can find android plugin version by go to menu

File > Project Structure > Project

Then Sync Again. If you see this warning, ignore it.

3rd-party Gradle plug-ins may be the cause

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Sowattana Sigen
  • 202
  • 2
  • 10
6

Try this.Andrid studio 2.0(2.1)

In build.gradle

android{
   dataBinding {
        enabled = true
    }
...
}
dependencies {
 kapt 'com.android.databinding:compiler:2.0.0-rc1'
....
}

kapt {
    generateStubs = true
}

In my project: buildToolsVersion = "23.0.3"

in top level build.gradle

dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
    }
Garf1eld
  • 598
  • 3
  • 7
  • 21
6

this work for me in androidStudio ver3.1.3

apply plugin: 'kotlin-kapt'

dataBinding {
    enabled = true
}

show usage sample

Zoe
  • 27,060
  • 21
  • 118
  • 148
emad pirayesh
  • 654
  • 7
  • 12
4

Configuration data binding in kotlin

build.gradle (folder app)

apply plugin: 'kotlin-kapt'

android {
   ...
   dataBinding {
      enabled = true
   }
}

dependencies {
   // data binding
   kapt "com.android.databinding:compiler:3.1.3"
}

Enjoy Kotlin...

4

Important Update

You can see in documentation of Android.

The new compiler in version 3.2 is enabled by default.

So Just Update your Android Studio to V3.2 or newer. and remove all unnecessary config.

So just enable dataBinding in app level build.gradle.

android {
    dataBinding {
        enabled = true
    }
}

It will do all things for you automatically.

You can SAFELY REMOVE below lines-

  • Remove databinding.compiler

    kapt 'com.android.databinding:compiler:3.0.1'
    
  • Remove kapt

    kapt {
        generateStubs = true
    }
    

My complete config

build.gradle (Project)

kotlin_version = '1.2.71'    
classpath 'com.android.tools.build:gradle:3.2.0'

Use gradle latest version. Use kotlin latest version.

build.gradle (App)

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

compileSdkVersion 28
targetSdkVersion 28

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Important Do not just copy and paste config. See this answer for setting up Kotlin version.

gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
4

In my case, the error was Unresolved reference: RegisterationUserBinding I just used my layout name fragment_registeration_user like this FragmentRegisterationUserBinding and made it in the Databinding layout and the error went away.

4

In the Gradle module file add this

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

To use databinding in Kotlin you need to configure your app to use data binding, enable the dataBinding build option in your build.gradle file in the .app module and you can replace your code with this:

import com.example.app.databinding.FragmentDataBdinding

class ProfileFragment : Fragment() {

    private lateint var mBinding: FragmentProfileBinding

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data, container, false)

        return mBinding.getRoot()
    }
}

For more help check the databinding documentation link: https://developer.android.com/topic/libraries/data-binding.

Tom
  • 16,842
  • 17
  • 45
  • 54
Hitesh Patel
  • 183
  • 2
  • 12
3

Try adding this to your gradle.properties

android.databinding.enableV2=true
Bhavin Patel
  • 872
  • 13
  • 30
2

Add following in you app build.gradle

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

This will do the trick.

$android_plugin_version is version of com.android.tools.build:gradle in application build.gradle

Also, add this to your module build.gradle

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

Randheer
  • 984
  • 6
  • 24
1

Add below build features in your app build.gradle file:

android {
    ...
  buildFeatures {
      viewBinding true
  }
}

Then in your activity onCreate method:

binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
SerjantArbuz
  • 982
  • 1
  • 12
  • 16
0

Add Databinding in android Project using when you have use kotlin language.

Below steps

--First you need to add the below plugin

**apply plugin: 'kotlin-kapt'**

--Second dataBinding enabled true

**dataBinding {
        enabled = true
    }**

All this point added in app.build.gradle after hit "SYNC NOW"

Lets For example you have edit profile activity then how to define binding variable in kotlin??

lateinit var buildProfileBinding: ActivityBuildProfileBinding

buildProfileBinding = getBinding()

Here,get binding is method to handle which type of binding object

protected <T extends ViewDataBinding> T getBinding() {
                return (T) binding;
            }
0

In my case, adding

kapt {
    generateStubs = true
}

Solved the problem for me. I ignored it the first time, I thought it's irrelevant to the problem:

Unresolved reference databinding

But now, data-binding is working just fine.

Rickless
  • 1,377
  • 3
  • 17
  • 36
0

I want to share my own expirience. To use data databinding with Kotlin in android studio is enough to add

dataBinding {
    enabled = true
}

After that "sync it" and, it's very important, to "make Project". After that all your object will be active to use.

Zoe
  • 27,060
  • 21
  • 118
  • 148
gloomyad
  • 21
  • 2
0

Before you try to use FragmentDetailsBinding you have to make sure you converted the corresponding layout( fragment_details.xml ) to data binding layout by wrapping the whole layout in "" tag parent and move all of xmlns to layout tag then build the project and thats it

TarekB
  • 757
  • 14
  • 20
0

In my case I only forgot to add in layout file the header:

<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">

....
Alexey Simchenko
  • 333
  • 3
  • 15
0

In your Gradle module (app) file add

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

BTW, keep in mind: Generated view binding name is based on name of your layout file, NOT on name of your class!

That means, if you have MainActivity class with corresponding activity_main.xml, the binding will be called ActivityMainBinding.

Also, do not forget to initialize your binding variable by adding

binding = ActivityMainBinding.inflate(layoutInflater)

into your onCreate() method.

Do not forget to add this as well:

setContentView(binding.root)

instead of setContentView(R.layout.activity_main) (that would cause your listeners to not work at all)

Firzen
  • 1,909
  • 9
  • 28
  • 42
0

I tried everything in this post and other parts of the internet but continued with the problem. Finally figured out that the folder name was too long, and when I built the app this "unresolved reference databinding" error appeared, but there was nothing on logcat about long name folders. I was about to give up when for some reason I tried moving the project to the desktop and inside a short name folder and problem solved!

So if your project is inside a destination like this:

C:\Users\Daniel\Documents\Udemy\Kotlin courses\2023\...very long name folder and very nested...\databindingProject

Just move it to:

C:\Users\Daniel\Desktop\Kotlin courses\databindingProject

Open it and it should build. If not try invalidate caches and restart.

But what caused it? I think that when Android Studio do the build process it generates a lot of files and maybe because of the long name folders and the folders nested inside other folders, some files are not created because Windows doesn't allow it, and that causes the error at the end.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459