Android - DataBinding - How and when the Binding classes will be generated?
Asked Answered
M

20

77

DataBinding Guide States

  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.

When will the Binding class , here say ActivityMainBinding, will be generated. I have compile time error. "cannot resolve ActivityMainBinding".

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

Any help is appreciated. Thanks

Media answered 12/7, 2015 at 7:59 Comment(6)
@DerGol...lum, Ya i know, it is beta release. I just want to try it out.Media
According to this Paragraph it is ok from Google's perspective to publish apps using this library. You just have to keep aware of the beta status and the implications: *** Developers should feel free to publish apps built with the Data Binding library beta release, with the caveats that the standard Android SDK and Google Play terms of service apply, and it’s always a great idea to test your app thoroughly when adopting new libraries or tools.Bowstring
Can anyone point to where the generated classes/files are located in the project?Superbomb
Just for the completeness : all generated code is inside "module_dir"/build/generated. Further below as per resources there is res directory as per java classes there is src with affinities (e.g. dataBinding). This structure is generated by gradle 2.2+Peptonize
In my case, the databingclass is updated timely if there is element <data></data> in the xml file, or it is only updated after reopening the studio IDE.Matchboard
3 years later and Android Studio still doesn't generate the binding files reliable. PRO TIP: avoid MVVM in Android.Bateman
I
99

What is your layout name?

The above layout file was activity_main.xml so the generate class was ActivityMainBinding.

What this means is that the generated class name will depend on your layout's name

activity_main.xml -> ActivityMainBinding.java

I think your activity name is "main_activity", so the generated binding class name should be MainActivityBinding not ActivityMainBinding

Inculpate answered 27/7, 2015 at 9:3 Comment(4)
It's definitely confusing in this case that classes are postfixed with "Activity" while xmls are prefixed!Dressmaker
This doesnt answer the question of "how and when". I'm having the same issue as the OP, the binding file is NOT GENERATED for me. This answer just tells you about the naming convention, and doesnt give any clue as to how to resolve the issue of the missing file.Dumbhead
@Dumbhead I don't know 'How & When', but I had a similar problem, and what fixed it for me was putting all of the xmlns:app="schemas.android.com/apk/res-auto" stuff in the layout tag instead of the top view tag. It was just an oversight on my part, but it was driving me crazy, so I figured I'd pass it on in case it helped someone else.Warrington
Kindly help me i have a package name like com.asadmukhtar.show and xml file name is activity_splash, after data binding enable my binding file always generate in package like com.example why this happen i am following MVVM model. kindly help meFiasco
S
35

When it's not generating the binding class, I restart Android studio. Then the binding class will be generated. Isn't it caused by cache of android studio?

BTW, if you are using android-apt, please check it. Because it will cause binding class not to be generate.

Som answered 20/11, 2015 at 7:9 Comment(5)
yes restart worked and issue is still there in Android Studio 2.1Cursed
True and better to Invalidate cache And restart ... that happens if you activate Databinding after creating layout..Philanthropic
As 08/16 I have this issue if more than one instance of AndroidStudio is open. I had to restart to see the binding suffix class.Undertone
with me, the binding file exists in \Project\app\build\generated\source\apt\development\debug\project\android\app\databinding HOWEVER Android Studio 3.1.3 is reporting the class as Unknown. Invalidate Caches and Restart is not fixing it.Bateman
also, Android Studio keeps generating an error com.intellij.psi.PsiInvalidElementAccessException: Element: class com.intellij.psi.impl.source.xml.XmlFileImpl because: different providers. What a waste of time !Bateman
S
32

Did you update your layout file for data binding? They are generated only for layouts which have data binding.

It has to start with a layout tag which has 2 child tags (data & your root view).

Something like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
   <data>
       <variable name="user" type="com.example.User"/>
   </data>
   <LinearLayout ...
   </LinearLayout>
</layout>

When your layout has this form, AndroidStudio should auto complete the class. Also, by default, it is generated in <your.app.package>.databinding package.

Stroboscope answered 12/7, 2015 at 8:57 Comment(4)
Even if you're not using Android Studio, the gradle plugin will generate the code during the annotation processing stage. Without Android Studio, you'll have to have faith that the class will be generated and import the Binding class yourself. Something like "import com.my.package.databinding.ActivityMainBinding;" for activity_main.xmlBohannon
Class wasn't generated when I had only <layout> and no <data>. When I added <data> with some <variable>, class got generated.Febrifuge
Thanks for this answer, no <data> tag was my problem. Even works without adding a variable, by the way.Mastiff
This solved it for me. That layout section is needed for the binding to be generatedDaina
J
16

Rule

Layout name is in snake_case, and generated binding class name will be PascalCase.

If you layout name is activity_home.xml then binding class name will be ActivityHomeBinding.class.

Problem

  1. Many times you don't get import suggestion of DataBinding class.
  2. Binding class is not generated when there is some issue in layout.
  3. Binding class are not available when build is failed

Here is hack

When you Don't get Import Suggestion

  • When you don't get import suggestion. Import manually your binding class like this. (IDE often does not show suggestions for binding classes)

    import <yourpackage>databinding.ActivityMainBinding;
    

Import line still shows error?

  • If your import line shows error, then try make project (ctrl + F9) / Build> Make Project. .
    1. If Build is failed due to some error, then solve it.
    2. If build is successful then binding class will be generated.

Quick hack for generating binding class-

  • If your binding class not generated then close project (File > Close Project) and open from recent.

Note that I recommend close and open from recent because it takes less time than Rebuild / Restart IDE.

Quick hack for generating layout variables in binding class-

  • If your layout data variable are not generated then close project (File > Close Project) and open from recent.

If you still have issues. Let me know in comments, or see this answer for better understanding.

Jodhpurs answered 3/10, 2018 at 5:51 Comment(0)
T
15

Try to rename layout to main_activity.xml.

In my case, it didn't work to generate binding class for "activity_main.xml".
But renaming the layout file to main_activity.xml worked just fine.

Troll answered 16/11, 2015 at 18:0 Comment(1)
It worked for me too. From now on, I will use ´xxxxxx_activity.xml´ for all of my activities/fragments as a new naming convention. Thanks!Bowlin
S
4

Make sure that the layout of the:

 <data>
   <variable name="user" type="com.example.User"/>
 </data>

Is in the activity_main.xml if you are looking for ActivityMainBinding. In most boilerplate projects you set your content view to activity_main.xml, but then inflate you fragment_main.xml.

If you put your <data> in fragment_main.xml layout then the class that is generated will be FragmentMainBinding.

Note: This may seem obvious after reading, but it is something that can be easily overlooked when following the android documentation.

Superbomb answered 29/9, 2015 at 14:56 Comment(0)
B
4

If you ever wanted to give your own Binding class name just add class attribute to the data element with class name

Binding classes may be renamed or placed in different packages by adjusting the class attribute of the data element.

<data class="ContactItem">
    ...
</data>

<data class="com.example.ContactItem">
...
</data>
Berri answered 27/4, 2016 at 10:45 Comment(1)
Restarting Android Studio as posted by @Frank Cheng does work, However it makes it tedious to restart it every time a new layout is created. I opted for this option of naming the binding classes my self as it seems to work without problems.Pyrochemical
C
4

In my case Restarting Android Studio does work. It is bug in android-apt

Candace answered 6/9, 2016 at 9:56 Comment(0)
R
2

Just a simple restart didn't work for me. I had to Invalidate Caches and Restart then I could see the binding classes. It's under the File menu for those who don't know.

Rimarimas answered 17/11, 2016 at 5:13 Comment(0)
O
1

For android databinding to work properly you have to use android tools for gradle (com.android.tools.build:gradle) >=1.3.0.

So your project build.gradle must look like:

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

allprojects {
    repositories {
        jcenter()
    }
}

And module build.gradle must have that plugin:

apply plugin: 'com.android.databinding'

After all, check in your module you're using latest buildToolsVersion (right now it is 22.0.1). I am not sure that's required but it possibly will make you feel good about you're on the "bleeding edge of technology" ^_^ :

buildToolsVersion '22.0.1'

Resync gradle and rebuild your project. It is likely possible that without rebuild of project you might not get SomeLayoutBinding classes generated.

In Android Studio that could be done from application menu: Build -> Rebuild project

Overthecounter answered 15/8, 2015 at 14:29 Comment(1)
this will cause error posted in #35251456 (Error:(3, 0) Cause: org/apache/commons/lang3/StringUtils)Tenderhearted
D
1

Faced the same issue.

Reason for "cannot resolve ActivityMainBinding" is that your Binding file isn't generated. Try to clean and rebuild project. Also make sure you have followed the steps :

  1. classpath "com.android.databinding:dataBinder:1.0-rc4" --> include this in main module build file
  2. apply plugin: 'com.android.databinding' to your app module you are building
  3. Clean
  4. Rebuild. Check under ,if build->indermediates->your package name->databinding folder is generated containing ActivityMainBinding class.

Alternatively if you want to see the generated source.

  1. classpath 'com.neenbedankt.gradle.plugins:android-apt:1.7' -->apply to your main module.
  2. apply plugin: 'com.neenbedankt.android-apt' --> to you app module
  3. apt 'com.android.databinding:compiler:1.0-rc0' --> include in your dependencies.

These classes will be generated on first build. Also make sure the applicationId in your application module is same as the package name in AndroidManifest.xml of your app module. Hope this helps.

Doralynne answered 26/12, 2015 at 10:18 Comment(0)
B
1

My experience is that Android Studio 3.1.3 generated the databinding class after I clicked "Build > Rebuild Project". The file was stored in:

\Project\app\build\generated\source\apt\development\debug\project\android\app\databinding

However, Android Studio still reported the binding class as "Unknown" in source code.

To finally fix it, I manually added the import statement:

import project.android.app.databinding.*;

Bateman answered 31/7, 2018 at 10:22 Comment(0)
V
0

A weird "bug" in android-studio causes the generated BR.java file not to use the @Bindable fields and still only have the _all property if a res/layout directory doesn't exist.

It happened to me when I wanted to create a "No Activity" App to have a library that contained my different bindable data.

Ventriloquy answered 7/9, 2016 at 15:42 Comment(0)
I
0

In my case i just enclosed my layout xml in <layout></layout> tags and that's it, without adding the data tag, i was successful to generate Data Bindings. Hope this helps.

<data>
       <variable name="user" type="com.example.User"/>
</data>
Incult answered 8/3, 2017 at 12:8 Comment(0)
O
0
<data class="MainActivityBinding">
    <variable
        name="user"
        type="com.example.administrator.my_mvvm.User" />
</data>

//Remember need Build-> Rebuild Project

Osteoid answered 15/9, 2017 at 15:29 Comment(0)
U
0

check the fields access level of your object, when i turned public it worked here

Undemonstrative answered 31/1, 2018 at 19:5 Comment(0)
A
0

If you don't want to restart android studio, one way is to rename activity_main.xml to something else e.g activity_m.xml and then rename it back to activity_main.xml. It is much faster than restarting android studio.

To rename, right click on activity_main.xml and choose Refactor => Rename

Aili answered 21/5, 2018 at 8:39 Comment(0)
S
0

I ran into a similar issue that hasn't been mentioned here yet. In my case, I incorrectly added <Layout> as the tag versus <layout>. <Layout> is apparently a valid tag because Android Studio didn't complain (other than requiring layout_width and layout_height which aren't required for <layout>). The capitalization difference will manifest in similar behavior where you cannot import the databinding class (import com.example.android.aboutme.databinding.ActivityMainBinding in my case) in the MainActivity class even though <Layout> is a valid tag and the build.gradle file is defined properly to support data binding.

In my case, I did not need the <data> tags defined yet in order for ActivityMainBinding to validly import and be referenced in:

private lateinit var binding: ActivityMainBinding

I was working through the this codelab when I ran into this behavior: https://developer.android.com/codelabs/kotlin-android-training-data-binding-basics/index.html

Sleazy answered 26/11, 2020 at 13:20 Comment(0)
H
0

Hi maybe you can try this as well include this in build.gradle(:app)

inside the android block

buildFeatures { viewBinding true }

worked for me, maybe it could for you as well

Harlow answered 1/5, 2021 at 4:26 Comment(0)
A
0

activity_main.xml file needs to start with layout tag as shown below.

Anthroposophy answered 14/9, 2021 at 18:3 Comment(2)
<layout xmlns:android="schemas.android.com/apk/res/android" xmlns:app="schemas.android.com/apk/res-auto"> </layout>Anthroposophy
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewThreadfin

© 2022 - 2024 — McMap. All rights reserved.