145

I am using Data Binding in my project, when using <layout> and <data> in my xml binding class is not generated.

For example i have activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>    </data>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </RelativeLayout>
</layout>

Now if i am writing ActivityMainBinding in my activity/fragment it shows error that class is not available. But after including <variable> in my xml file, it is able to generate ActivityMainBinding class.

Android Studio : 2.1.3
Classpath : com.android.tools.build:gradle:2.1.3
minSdkVersion 16
targetSdkVersion 24
buildToolsVersion 24.0.0

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • 2
    is `dataBinding.enabled` in your build.gradle? – pskink Sep 14 '16 at 05:41
  • 2
    I think this is a known error. You can try to build your project before you try to access `ActivityMainBinding`, or it has to do something with [this](https://code.google.com/p/android/issues/detail?can=2&q=222194%20&colspec=ID%20Status%20Priority%20Owner%20Summary%20Stars%20Reporter%20Opened&id=222194) bug. – yennsarah Sep 14 '16 at 05:41
  • @pskink yes it is, that is why it is generating binding class after adding `` in xml – Ravi Sep 14 '16 at 05:44
  • @Amylinn after building my project it generates, but my question is when i write ``, it generates binding class without building project. – Ravi Sep 14 '16 at 05:45
  • ah, indeed, i missed that – pskink Sep 14 '16 at 05:53
  • 1
    I'm confuse about the real question? if adding can solve the problem, why don't you do that? i don't get the point of binding without the ViewModel () – ktutnik Sep 16 '16 at 07:33
  • Why should i add `` when i dont need it? – Ravi Sep 16 '16 at 07:37
  • @RaviRupareliya did you try to `Restart` the `Android Studio`.. – Harshad Pansuriya Sep 21 '16 at 09:14
  • @Ironman yes, i have tried with restart, invalidate and restart also, but it didn't help – Ravi Sep 21 '16 at 09:18
  • @RaviRupareliya i Think the problem is in `android-apt` just check it out.. – Harshad Pansuriya Sep 21 '16 at 09:19
  • What is the purpose of using data binding without a variable in your layout? – Tin Tran Sep 21 '16 at 15:29
  • When there is error in xml file at that time this type of error is generated. so upload code which contains error. (With variable tag) – Khyati Vara Feb 28 '17 at 09:41
  • @KhyatiFatania Hope you have read the question properly, i have mentioned that **But after including in my xml file, it is able to generate** – Ravi Feb 28 '17 at 10:07
  • see this link : https://codelabs.developers.google.com/codelabs/android-databinding/#2 and add : in module gradle apply plugin: 'kotlin-kapt' – Geet Thakur Dec 30 '19 at 06:12

35 Answers35

373

I did not get any satisfying answers. So here are the tips which are summary of my data binding knowledge.

Tips For Solving DataBinding Issues

Update

To get more accurate errors and suggestions, I strongly recommend to update Android Studio and Gradle plugin version to the latest. Because I am not facing many issues after AS 3.2 version.

See Latest Android Studio, and Latest Gradle Plugin.

Orignal Solution

After reading this answer, you will not get stuck in data binding auto generation issues for both Classes and Data Variables.

Check these points one by one. Any of these can make your work done. Point 3 to last are really important, so don't miss them.

1. Check if data-binding enabled

You should have data binding enabled in build.gradle. If not then add this and Sync.

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

2. Check layout is converted in binding layout

Now if you want data binding class to be generated then you should wrap xml layout with data binding (<layout tag). Something like this.

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

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

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

Along with this check whether the binding variable names are correct as in the view model class

3. Auto-generated Binding class name?

Your data binding class should be generated after creating binding layout.

If your layout name is in snake case activity_main.xml then data binding class will be generated in camel case like ActivityMainBinding.

4. Can't See Import Suggestion?

Sometimes when you type ActivityMai..., then it does not show suggestion, in that case import manually.

import <yourpackage>databinding.ActivityMainBinding;

5. Read Build Fail Logcat

Your binding class and new variables in layout will not be generated if your build fails. So first Make project by Ctrl + F9 (Build > Make project).

  • If a build fails then see what is an error, usually we have errors in layout fields. Error logs will point out the error line number with the issue.
  • Binding may fail cause some stupid error, like syntax error or missing import. In that case, you will get logcat full of errors of binding classes. But you should read complete logcat to find appropriate issue.

6. Close and open project from recent

I always do this because it takes much less time than Rebuild / Make project.

  • Close project from File > Close Project
  • Open again from recent

Note that I prefer Close and Open from Recent because it takes much less time than Rebuild / Restart IDE.

7. Rebuild Project

If still your class is not generated. (Some time when we paste layout file, then it happens). Then Rebuild Project from Build> Rebuild (Not Build or Make project). It will generate your data binding class. (Rebuild does Magic for me.)

8. Have latest Android Studio

After updating AS to Android Studio 3.2, I felt many bugs fix in data binding auto generation. So you should also have the latest AS.

#Solution for <variables

<data>
    <variable
        name="item"
        type="com.package.Model"/>
</data>

Usually, when we put a variable in layout, it creates a getter and setter of it. And we can use binding.setItem(item); and binding.getItem();, but if you can't see those methods then read the below information.

1. Close and open project from recent

If you have created a data variable - <variable in your layout and it does not show up its setter and getter in data binding class, then Close and Open from Recent your project.

2. Clean project after changing the type

If you changed the type of some <variable in your layout and getter setter type is not changing then Clean project (Build> Clean Project)

Final words

Finally if still your binding class is not generated, then we have our most powerful weapon. - Restart Android Studio

  • First, try just restart, this always generates variables of my binding layout after restart.
  • If it does not work then Invalidate Cache & Restart.

This is all that i do to solve my data binding errors. If you get any further issues, you can comment here.

Boken
  • 4,825
  • 10
  • 32
  • 42
Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • 2
    If the problem continues... (8) Invalidate & restart.... if not resolved, (9) change dataBinding { enabled = false } ... build, and then dataBinding { enabled = true } build again.... – PravyNandas Aug 21 '18 at 22:02
  • https://stackoverflow.com/questions/49870616/android-studio-can-not-generate-binding-class-while-use-databinding – samus Sep 11 '18 at 17:01
  • 1
    In my case, I had to import the classpath manually for some reason the IDE does not show this as a solution. Tnx :) – Ivan Kaloyanov Sep 23 '18 at 11:37
  • You could also add that the "import android.R" must be removed, if its part of the import list. This solved my problem with Unresolved reference to the activity xml file – Tim John Aug 31 '19 at 14:32
  • 3rd point is more important, my class name was "CommentsDialog" and layout file was "fragment_comment_dialog" and the generated binding file was "FragmentCommentDialogBinding" – Sony Jan 30 '20 at 07:12
  • Very useful. Unfortunately, NONE of these suggestions work for me. Almost comically, My project compiles and runs just fine, while LITTERED with error messages. Wouldn't it be nice if chasing binding classes around all day every day wasn't something every Android developer had to add to their workload? I'm so very tired of doing this. Dear Google, please fix data binding in Android Studio. – rmirabelle Mar 31 '20 at 16:05
  • If even Invalidate & restart... In my case I deleted a BindingAdapter method which was linked with an attribute called "image", but the layout didn't notify with an error the line where I used "app:image=bla bla" and the compilation crashed in the DataBinderMapperImpl where was trying to import the non generated ActivityBlaBindingImpl (since in the XML there was an error). So check if you also forget to change an attribute. – corrado4eyes Apr 20 '20 at 11:36
  • I find Updating the gradle plugin tends to break the entire project forever rather than fix anything – Ethan McTague Oct 24 '20 at 18:17
  • In my case there was nothing wrong. I did Build > Make project and then it was successful. Thanks. – Abhinav Chauhan Oct 27 '20 at 06:03
  • As to Android Studio 4.1, the correct way to add databinding in the gradle files is: android { ... buildFeatures { dataBinding true } ... } maybe you'd like to edit your answer as it's a very popular issue/answer – Blueprint Nov 20 '20 at 12:46
  • I tried all this variants and helped only to rename layout file, for example rename activity_home1.xml to activity_home2.xml then use ActivityHome2Binding class. "excellent" magic – Elron Feb 08 '21 at 16:44
  • Good options thanks we just need to confess binding is broken. – Samir Jan 08 '22 at 11:05
  • @khemraj i like your method of answering. thanks. please see this question i have searched a lot for the answer but unable to find the solution. https://stackoverflow.com/q/74821228/6540548 see if you may find the solutions. Thanks – Fazal Dec 16 '22 at 07:17
  • In my case, is not needed in step 2. I used . – zxcisnoias Mar 12 '23 at 18:12
47

DataBinding class generated automatically.

if your xml name is activity_test then the Binding class will be ActivityTestBinding.

but,

dataBinding {
        enabled = true
    }

layout should have layout as root

<layout xmlns:android="http://schemas.android.com/apk/res/android">
</layout>
ViramP
  • 1,659
  • 11
  • 11
19

I had the same issue. After reading over the android sdk docs, there is only the expected file name to be created but nothing about what to do if it does not happen. I noticed after some more research that after removing the namespace to the layout element like below (using your example), it worked for me.

    <?xml version="1.0" encoding="utf-8"?>
    <layout>
        <data>  </data>
        <RelativeLayout
           xmlns:android="http://schemas.android.com/apk/res/android"
           android:layout_width="match_parent"
           android:layout_height="match_parent">
        </RelativeLayout>
    </layout> 
ngaspama
  • 371
  • 4
  • 10
  • 1
    Here in 2021, I still believe this is a bug with Artic fox 3.1 patch 3, but ater wraping the xml with the layout tag with no extra properties my ide stoped showing the databinding auto generated classes in red. My ide showed them in red, but everything compiled fine. – mickecast Oct 27 '21 at 17:59
  • +1 It helped to solve my issue. Still not happy about solution. I have another project that doesn't have the and binding still generates there. – StahlRat Aug 07 '22 at 02:52
11

In my case, the Binding class was generated and in place ( but I thought it wasn't) ... but it does not automatically add import of said class to the activity/fragment import section... so... OPTION + ENTER :)

  • 2
    Bingo, worked for me, though I had to type out the import manually, intellisense wasn't offering the option for whatever reason. – Rob May 28 '18 at 20:09
9
dataBinding {
        enabled = true
    }

To enable the new data binding compiler, add the following option to your gradle.properties file:

android.databinding.enableV2=true

Update:

To enable databinding please use,

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

Please follow this link: https://developer.android.com/jetpack/androidx/releases/databinding

Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
9

if you do base job, for enable databainding in your project, like use enable in gradle and use layout tag in xml, when you change xml code and did not generat new databinding class for those xml you can use a fast way for generation only data binding class in gradle->other->databindinggenbaseclassesDebug it fast more than bulid whole project. its generate only databinding class. enter image description here

Mahdi Azadbar
  • 1,330
  • 3
  • 17
  • 24
8

After having set up it properly (including xml namespace and wrapping everything into <layout>), the one which worked for me was doing Build -> Make project. Nor Clean Project or Rebuild Project did. I'm in Android Studio 2.3.1, using 26.0.2 build tools. There's no need for <data> tags.

Aritz
  • 30,971
  • 16
  • 136
  • 217
  • This should be marked as the correct answer. Rest all are just workarounds. No need of moving namespaces or even adding data element – Vicky Kapadia Jun 05 '18 at 17:35
6

My solution was to take as a suffix FragmentBinding in the class name.

A binding class is generated for each layout file. By default, the name of the class is based on the name of the layout file, converting it to Pascal case and adding the Binding suffix to it. The above layout filename is activity_main.xml so the corresponding generated class is ActivityMainBinding. This class holds all the bindings from the layout properties (for example, the user variable) to the layout's views and knows how to assign values for the binding expressions.

The nomenclature of the name of the activity or fragment class may vary in terms of prefixes. Because the suffix is always Binding.

After following the response of Khemraj and Invalidate Caches / Restart, you should rewrite ActivityBinding or FragmentBinding to get the IDE suggestions of the classes that were already generated and DO NOT hardcode the import.

In my case I was trying to import the name of the class backwards be FragmentCompetitionsBinding instead of CompetitionsFragmentBinding.

GL

Source

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
5

I had the same problem. I made a mistake while I refactored. The autogen binding class has its name from the xml layout file.

fragment_name.xml -> FragmentNameBinding

writer_chris
  • 146
  • 3
  • 9
3

Most of time it just need to rebuild. not build not make project . and it will be better if you first of all do invalid Caches and restart Android studio then clean and rebuild it .

Arezou
  • 31
  • 2
2

Data binding classes are generated during the build so after you enable data binding in the Gradle build of the app and surround your xml with the layout tag you should rebuild your app. If that doesn't help, delete your build folder and do it again.

Schadenfreude
  • 1,522
  • 1
  • 20
  • 41
2

I do not know it will work for you or not. Just rename the layout XML file name. Like suppose your layout name is activity_main.xml just change rename it to anything like main.xml and again rename it to activity_main.xml. Then you can able to see the import option on ActivityMainBinding.

Hope it works for you.

Sudhansu
  • 780
  • 1
  • 9
  • 28
2

Thanks to this answer here - it looks like the "layout namespace" needs to either be cleared out, or you need a new unique name.

Here are the options that worked for me:

  1. Create a fresh name for the layout to make sure it can be generated. This solved my issue, where I had a layout that was first created, without data binding - let's call it fragment_abc.xml. When I tried to add data binding to it, it was not recognized - even after multiple clear cache & restart calls. However, soon as I made a copy of the layout fragment_abc2.xml, immediately I got the generated data-binding .java/.class object.

  2. After seeing the above work, I tried to just remove the /build folder from the module, and rebuilt the project - this worked to get data binding for the original layout.

Gene Bo
  • 11,284
  • 8
  • 90
  • 137
1

When you work with a multimodule Android application check your binding class path. Maybe you should use:

import com.yourcompany.app.android.modulename.databinding.FragmentABCtBinding insted of:

import com.yourcompany.app.android.databinding.FragmentABCtBinding

1

In my case, I thought that generated class had to appear with my usual classes in src folder. In addition, I thought that the name of the generated class should be slightly different. It all was my mistake. The generated class can be found in build folder, build -> generated -> ... path. If there is no import of the generated class in your activity, add the import

import com.yourcompany.app.databinding.ActivityMainBinding;"
Yash
  • 11,486
  • 4
  • 19
  • 35
Kseniya
  • 11
  • 1
1

Delete layouts and undo, and make sure the generated binding classes are imported correctly after that.

Ahmed AlAskalany
  • 1,600
  • 1
  • 13
  • 13
1

Make sure data binding enabled

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

Sync project with gradle dan click the button (Sync project with Gradle)

fahrizal89
  • 598
  • 5
  • 13
1

If answer did not work for you, then my recommendation is simple but effective.

The idea is to determine which is the component that is generating the problem. To do this, comment on all the lines of your custom_fragment.xml and its uses in the CustomFragment.kt and leave something minimalist like the following.

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

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</layout>

Then run the app and add component to component while you Apply Code Changes (Ctrl+Alt+F10) to the execution of the app until the app crashes, that is when you found the fault.

Data binding logs are sometimes not so descriptive and this is a generic strategy to find the faulty component.

GL

Braian Coronel
  • 22,105
  • 4
  • 57
  • 62
0

The only thing I can imagine if possible is if you don't have

dataBinding {
    enabled true
}

in your gradle file. If not just add it to the gradle file. i.e

android {
  ......

  dataBinding {
    enabled true
  }
}

then sync your project. If it still fail, you may need to do Invalidate/Restart of your android studio

  • I have clearly mentioned in my question that after adding `` in xml it is generating Binding class, so there is no case of not adding `dataBinding` in gradle file, if i have not added than it should not generate binding class. – Ravi Sep 21 '16 at 02:56
  • Before Synching and restarting. Please try to 'Make'. It will workout. – Nizamudeen Sherif Apr 04 '19 at 09:22
0

I had same problem. Everything you done correct. Thing is you need add variable inside data tag in xml. For that you should create a sample model class and add it as variable in data tag.

Until that you won't get to see generated ActivityMainBinding.

0

1.Add Below in app gradle

 dataBinding {
        enabled = true
    }

2.In xml layout write below code

<layout
    xmlns:android="http://schemas.android.com/apk/res/android">
  <data></data>
</layout>if you don't get data binding class just rename the layout file name and you will get data binding class.
Rohan Lodhi
  • 1,385
  • 9
  • 24
0

I had a similar issue where I had the layout wrapped and my data binding enabled in the gradle file. Main activity still couldn't intellisense or see my classes. What fixed it for me was adding the binding variable and importing the binding anyway. From there I just built the solution and then it seemed to know what the class was. From there I was able to import my camel case classes that were generated.

stegnerd
  • 1,119
  • 1
  • 17
  • 25
0

I got the issue and the problem was in the layout the field used was not a String, it was a Date.

Looks that all field got to be text to work, at least with the TexView component.

If you build with the command ./gradlew build --stacktrace

This show better the errors.

jactive
  • 71
  • 1
  • 7
0

If Recently any one migrated existing project into androidx then you need to replace your import from

import com.yourpackagename.BR;

to

import androidx.databinding.library.baseAdapters.BR;

After Google 2 days finally got solution, which one work for me.

Zala Janaksinh
  • 2,929
  • 5
  • 32
  • 58
Milan Sheth
  • 884
  • 12
  • 11
  • 1
    No. Binding Resource (*.BR.*) like Resource (*.R.*). It generated based on your project resource (id, drawable, color,...) so it will place inside your project package (`your.project.package.BR`). Not inside third party library like `androidx.databinding.library.baseAdapters.BR`. – dphans Oct 02 '19 at 08:01
0

In case you get the following error in DataBindingUtil.setContentView

Unresolved reference: activity_main

all you need to do is remove the following import statement

import android.R

I found the solution on another forum. Source

Tim John
  • 192
  • 2
  • 17
0

There are cases when you won't see a file under generated directory, you might be binding a property that is not declared in viewmodel. It doesn't essentially give you a lint error if you do so in xml.

Uzair
  • 1,529
  • 14
  • 17
0

If you are implement the Serializable -> you must implement the Serializable

else you will get this error. Hope it will help someone in future

In my case I use the Parcel library. I missed to annotate @Parcel in my sub class

Ranjithkumar
  • 16,071
  • 12
  • 120
  • 159
0

In addition to the above steps, you can also check the variable type. Make sure it's String for TextView or the same as defined in the BindingAdapter. For example:

data class MyDataObject(val name: String, val age: Int)

and in XML:

android:text="@{dataobject.age}"

This will cause the above error. To fix you can either make the age variable of type String or you can import String in your XML and use String.valueOf(age) as following:

<data>
    <import type="String" />
...
</data>

And in your TextView:

android:text="@{String.valueOf(dataobject.age)}"
shyam
  • 596
  • 9
  • 18
0

If there is an issue with your XML file, the Databinding class would not be generated. A quick fix would be to run through the XML file and check for syntax errors (which are usually highlighted in red). The errors might come in the form of non-existing or wrong references, typographical errors, etc.

In essence, just make sure there is no red-underlined line in your XML code. When you are done, rebuild and your Databinding class would have been generated.

halfer
  • 19,824
  • 17
  • 99
  • 186
Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69
0

In my case, data binding classes were not generated because I had deleted the mipmap Android Resource Directory. I recreated the res/mipmap/ directory and the data binding classes were reinstated.

buggily
  • 418
  • 2
  • 12
0

I encountered a similar issue where DataBinding failed to generate the BindingImpl class. In my case was an issue from a method in the data class where the name was used wrong: The model contained a method onSignInCliked() and in the layout I used onSigninCliked(). Notice the SignIn vs Signin.

The error message wasn't enough and I discovered the issue only when I used the build script with the stack-trace option.

Ionut Negru
  • 6,186
  • 4
  • 48
  • 78
0

I had all classes generated, but Android Studio did not see them and marked them as invalid imports. Running gradle sync solved the issue.

Android Studio - gradle sync

David Vareka
  • 252
  • 2
  • 6
0

After you check all the reasons in the accepted answer, make sure to match to the exact naming in the file.xml. In my case I had a tiny typo in my layout name.

cigien
  • 57,834
  • 11
  • 73
  • 112
0

I'd been through all these answers, and still no result, but I'd copied and pasted code from a different project and although the imports all looked the same (I'd not made that level of error, or so I thought), I deleted all the imports and then let Android Studio re-generate them.

I deleted these:

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import com.example.neadesv301.databinding.ListItemBinding

After the deletion, lots of things turned red e.g. RecyclerView, so I just deleted and retyped RecyclerView and Android Studio regenerated the missing imports and viola.

I'm guessing the imports are synced as the code is typed and if they're just copied and pasted that messes up that syncing process, though one would have thought that a re-sync would do just sort it, but I'm guessing.

As previously mentioned I'd done about 3 hours of everything else, first, see previous answers.

Lozminda
  • 45
  • 8
-5

use class path 'com.android.databinding:dataBinder:1.0-rc0'