Unresolved reference databinding - Android Studio 4.0 - android

I keep getting errors: "Unresolved reference: databinding" and "Unresolved reference: ActivityMainBinding".
I am using Android Studio 4.0, Android Gradle Plugin Version: 4.0.0 and Gradle Version 6.1.1.
build.gradle (Module: app):
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.twowaydatabinding"
minSdkVersion 24
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
dataBinding = true
viewBinding = true
}
}
dependencies {
def lifecycle_version = "2.2.0"
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
}
build.gradle (Project):
buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
activity_main.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:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="com.example.twowaydatabinding.MainActivityViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- layout content -->
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.kt:
package com.example.twowaydatabinding
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.example.twowaydatabinding.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var viewModel : MainActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)
binding.viewModel = viewModel
binding.lifecycleOwner = this
}
}
MainActivityViewModel.xml:
package com.example.twowaydatabinding
import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class MainActivityViewModel : ViewModel(), Observable {
#Bindable
val userName = MutableLiveData<String>()
init {
userName.value = "Frank"
}
override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
}
I tried:
Build -> Clean Project, then Build -> Rebuild Project
File -> Invalidate Caches / Restart
but nothing helps. Class ActivityMainBinding is never generting.
When I go to declaration of
import com.example.twowaydatabinding.databinding.ActivityMainBinding in MainActivity.kt it redirects me to activity_main.xml. Code doesn't show any errors, but when I try to build the project those databinding errors shows up.
What am I doing wrong?

Instead Of this line
buildFeatures {
dataBinding = true
viewBinding = true
}
Write this line
buildFeatures {
dataBinding true
viewBinding true
}
Try this in main Activity,
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

This worked for me
1) Delete ".gradle" folder , delte ".idea" folder and delete build folder under app folder
2) Click on "File -> Invalidate Caches / Restart"

Add data binding like this in your build.gradle(Module:app)
defaultConfig {
dataBinding {
enabled true
}
}

Related

Room Persistance Library: Cannot find implementation for ContactAppDatabase (ContactAppDatabase_Impl does not exist)

I am implementing Room database for storing contacts for the jetpack compose project on Android Studio Bumblebee 2021.1.1 Canary 10. But I am getting an error as shown below
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.tana.contactapp, PID: 8843
java.lang.RuntimeException: cannot find implementation for com.tana.contactapp.data.ContactAppDatabase. ContactAppDatabase_Impl does not exist
Here is my app-level Gradle file
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
compileSdk 30
defaultConfig {
applicationId "com.tana.contactapp"
minSdk 22
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
implementation "androidx.compose.material:material-icons-core:$compose_version"
implementation "androidx.compose.material:material-icons-extended:$compose_version"
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.0'
implementation 'androidx.room:room-ktx:2.3.0'
implementation 'androidx.compose.runtime:runtime-livedata:1.0.2'
implementation 'androidx.navigation:navigation-compose:2.4.0-alpha06'
annotationProcessor 'androidx.room:room-compiler:2.3.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"
}
Here is the project-level Gradle file
task clean(type: Delete) {
delete rootProject.buildDir
}
buildscript {
ext {
compose_version = '1.0.2'
}
}
Here is settings.gradle file
pluginManagement {
repositories {
gradlePluginPortal()
google()
mavenCentral()
}
plugins {
id 'com.android.application' version '7.1.0-alpha10'
id 'com.android.library' version '7.1.0-alpha10'
id 'org.jetbrains.kotlin.android' version '1.5.21'
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "ContactApp"
include ':app'
Here is my Entity File
package com.tana.contactapp.data
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Person
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
#Entity(tableName = "contacts")
data class Contact(
#PrimaryKey(autoGenerate = true) val id: Long = 0,
val name: String,
val number: String,
#Ignore val imageDp: ImageVector = Icons.Default.Person
)
Here is my DAO File
package com.tana.contactapp.data
import androidx.lifecycle.LiveData
import androidx.room.*
#Dao
interface ContactAppDao {
#Query("SELECT * FROM contacts")
fun getContacts(): LiveData<List<Contact>>
#Insert
suspend fun addContact(contact: Contact)
#Update
suspend fun updateContact(contact: Contact)
#Delete
suspend fun deleteContact(contact: Contact)
#Query("DELETE FROM contacts")
suspend fun deleteContacts()
}
Here is my Database File
package com.tana.contactapp.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = [Contact::class], version = 1, exportSchema = false)
abstract class ContactAppDatabase : RoomDatabase() {
abstract fun contactsDao(): ContactAppDao
companion object {
private var INSTANCE: ContactAppDatabase? = null
fun getDatabase(context: Context): ContactAppDatabase {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = Room.databaseBuilder(
context.applicationContext,
ContactAppDatabase::class.java,
"contact_app_database"
).build()
}
return instance
}
}
}
}
I have tried a lot of solutions from the previous questions similar to this but none seems to work for my case
You need to remove
annotationProcessor 'androidx.room:room-compiler:2.3.0'
and add room compiler using kapt
kapt androidx.room:room-compiler:$room_version
https://developer.android.com/jetpack/androidx/releases/room#kts
and kapt plugin, on top of your root gradle file
apply plugin: "kotlin-kapt"
I solved this by adding id 'org.jetbrains.kotlin.kapt' version '1.5.21' in settings.gradle file plugins section, and then adding id 'org.jetbrains.kotlin.kapt' in app gradle file instead of 'kotlin-kapt'

Starting out with Room, encountered this error: incompatible types: NonExistentClass cannot be converted to Annotation

I have looked at the solutions presented at each of these links.
NonExistentClass cannot be converted to Annotation - app:kaptDebugAndroidTestKotlin
-- Not relevant as I am not using JUnit5.
error: incompatible types: NonExistentClass cannot be converted to Annotation #error.NonExistentClass()
-- Two issues, one is I don't know where to put kapt { } and I tried leaving it as a global, but that didn't do anything and putting it in dependency caused a error.
NonExistentClass cannot be converted to Annotation
-- Unsure where to set generateStubs to true and where to set correctErrorTypes to true in my build.gradle file. I don't know if I can use annotationProcessor on it's own.
On my own I tried to implement android.arch before realizing it is deprecated.
I tried to use ksp but that returned an error stating that the complier doesn't know where the ksp() method is. Using
implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
did not resolve the error with ksp.
The error message exactly: "error: incompatible types: NonExistentClass cannot be converted to Annotation"
#error.NonExistentClass()
Here is my module build.gradle
plugins {
id 'com.android.application'
// id 'com.android.feature'
id 'kotlin-android'
id 'kotlin-kapt'
//id 'dagger.hilt.android.plugin'
//id 'kotlin-ksp'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android'
//apply plugin: 'dagger.hilt.android.plugin'
//apply plugin: 'com.android.feature'
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.testingdatabases"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
kapt {
correctErrorTypes = true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
// ROOM - -- - --- - - - >
def room_version = "2.3.0"
implementation("androidx.room:room-runtime:$room_version")
annotationProcessor "androidx.room:room-compiler:$room_version"
// To use Kotlin annotation processing tool (kapt)
kapt("androidx.room:room-compiler:$room_version")
// To use Kotlin Symbolic Processing (KSP)
// ksp("androidx.room:room-compiler:$room_version")
// optional - Kotlin Extensions and Coroutines support for Room
implementation("androidx.room:room-ktx:$room_version")
api("io.grpc:grpc-kotlin-stub:1.0.0")
// implementation("com.google.devtools.ksp:symbol-processing-api:1.5.0-1.0.0-alpha10")
// < -- - - - End of Room stuff
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Here is the project's build.gradle file,
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
def nav_version = "2.3.0-alpha01"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Here is the applications code,
package com.example.testingdatabases
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.RoomDatabase;
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
#Entity
data class User(
#PrimaryKey val uid: Int,
#ColumnInfo(name = "first_name") val firstName: String?,
#ColumnInfo(name = "last_name") val lastName: String?
)
#Dao
interface UserDao {
#Query("SELECT * FROM user")
fun getAll(): List<User>
#Query("SELECT * FROM user WHERE uid IN (:userIds)")
fun loadAllByIds(userIds: IntArray): List<User>
#Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
fun findByName(first: String, last: String): User
#Insert
fun insertAll(vararg users: User)
#Delete
fun delete(user: User)
}
#Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
in gradle implementation "a-b-x" is used and in kotlin dsl implemntation("a-b-x") is used ,don't mix
Your database is not build properly (According to me) Here

Build failed after adding Hilt components in Android project

I was trying to explore Hilt with simplest possible example, but my application isn't building. I added all the dependencies but when I try to build, it shows an error indicating not finding the hilt gradle plugin.
Here are my codes:
build.gradle(project)
ext.kotlin_version = "1.5.20"
ext.hilt_version = '2.35'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(app)
plugins{
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.bonny.tutorial.hilttest"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
//hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
Application Class (included in the Manifest too)
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
#HiltAndroidApp
class TextApplication : Application() {
}
Dependency class (MyTexts.kt)
class MyTexts #Inject constructor(){
val text = "Hello World"
}
MainActivity.kt
#AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var tv: TextView
#Inject lateinit var myTexts: MyTexts
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tv = findViewById(R.id.myText)
tv.text = myTexts.text
}
}
and the error looks like this:
public final class MainActivity extends androidx.appcompat.app.AppCompatActivity {
^
Expected #AndroidEntryPoint to have a value. Did you forget to apply the Gradle Plugin? (dagger.hilt.android.plugin)
See https://dagger.dev/hilt/gradle-setup.html
[Hilt] Processing did not complete. See error above for details.
Please suggest.
Kotlin 1.5.20 just came out (24 jun 2021) so there seems to be some compatibility issue. You can bring down to ext.kotlin_version = "1.5.10" in your build.gradle(project)
Also, Update hilt to latest 2.37
project build
classpath "com.google.dagger:hilt-android-gradle-plugin:2.37"
app build:
//Dagger - Hilt
implementation "com.google.dagger:hilt-android:2.37"
kapt "com.google.dagger:hilt-android-compiler:2.37"

Android Studio project doesn't generate binding object for the Main Activity

I took the Udacity course to learn developing Android apps with Kotlin, using data binding multiple times during it and having no problems enabling it, but now, trying to set up my first project, I am having some problems with it: Android Studio doesn't find the reference to the MainActivityBinding.
C:\Dev\Projects\Android_Studio\myproject\app\src\main\java\com\guglielmoboi\myproject\MainActivity.kt: (8, 35): Unresolved reference: MainActivityBinding
These are the files I produced:
build.gradle (project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
kotlin_version = "1.4.32"
}
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
build.gradle (:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.guglielmoboi.myproject"
minSdkVersion 26
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
**buildFeatures {
dataBinding true
viewBinding true
}**
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
/* Room dependencies */
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
/* Navigation dependencies */
def nav_version = "2.3.5"
// Java language implementation
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Kotlin
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
// Feature module Support
implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"
// Testing Navigation
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
// Jetpack Compose Integration
implementation "androidx.navigation:navigation-compose:1.0.0-alpha10"
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
activity_main.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:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
MainActivity.kt
package com.guglielmoboi.myproject
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity()
{
private lateinit var binding: MainActivityBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
Inside MainActivity
remove setContentView(R.layout.activity_main)
and add
val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
Use binding for all the UI stuff.

Can't fix error: Cannot find symbol class ActivityMainBindingImpl

I've got following error while trying to build prject with MVVM and data binding. I've searched through everything I could find here on StackOverflow, or common mistakes on the internet, but nothing worked for my case.
The only message I receive is this error. It looks like this in buildOutput:
I've had my packages named with capital letters and I've found here that this might be the cause because compiler treat them as names of classes, so I've changed them all to start with small letters, but that haven't helped.
I've created ViewModelFactory for creating my ViewModel inside Activity so I could send additional parameters with constructor using factory, so I've tried to remove it and use no parameters and create instance without using factory for this purpose, but still I havn't got any results (same error)
I was chaning both build.gradle's in different ways but result was always the same.
Finally I've deleted data binding and variable from XML, then I was able to run the app (with other errors, but I would be probably able to deal with those by myself) but I want to leave it as it is and just deal with my error.
I am not experienced with MVVM and data binding so it can be just a stupid mistake, but it is hard to find it if I don't know where I should look for it.
Here I post most important codes, if you need more then let me know:
build.grale(app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 30
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.rickmorty"
minSdkVersion 24
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures{
dataBinding = true
viewBinding = true
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.3.0-alpha02'
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "androidx.cardview:cardview:1.0.0"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'io.reactivex.rxjava2:rxjava:2.1.7'
implementation 'com.github.bumptech.glide:glide:4.6.1'
kapt 'com.github.bumptech.glide:compiler:4.4.0'
}
**build.gradle(project)
buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
MainActivity
class MainActivity : AppCompatActivity() {
lateinit var mainViewModel: MainViewModel
lateinit var mAdapter: CharactersAdapter
lateinit var api: CharacterAPI
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = RetrofitClient.instance
api = retrofit.create(CharacterAPI::class.java)
setupViewModel()
setupRecycler()
mainViewModel.getData().observe(this,
Observer<List<Results>> { t ->
mAdapter = CharactersAdapter(this#MainActivity, t!!)
rvCharacters.adapter = mAdapter
})
}
fun setupRecycler() {
val lManager = LinearLayoutManager(this#MainActivity)
rvCharacters.apply {
setHasFixedSize(true)
layoutManager = lManager
}
rvCharacters.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val visibleItems = lManager.childCount
val totalItems = lManager.itemCount
val firstVisible = lManager.findFirstVisibleItemPosition()
if (dy > 0) {
if (!mainViewModel.isLoading.value!! && (visibleItems + firstVisible) >= totalItems) {
mainViewModel.scrolledNext()
}
} else {
if (!mainViewModel.isLoading.value!! && (totalItems - visibleItems) <= 0) {
mainViewModel.scrolledPrev()
}
}
}
})
}
fun setupViewModel() {
mainViewModel = ViewModelProviders.of(this, MainViewModelFactory(application, api))
.get(MainViewModel::class.java)
DataBindingUtil.setContentView<ActivityMainBinding>(
this, R.layout.activity_main
).apply {
lifecycleOwner = this#MainActivity
viewmodel = mainViewModel
}
}
}
activity_main.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:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewmodel"
type="com.example.rickmorty.ViewModel.MainViewModel"/>
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="#+id/rlPageTitleHolder"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintHeight_percent="0.1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:layout_centerInParent="true"
android:text="#{() -> viewmodel.pageNumber}"/>
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/rvCharacters"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="#id/rlPageTitleHolder"
app:layout_constraintHeight_percent="0.9"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
As I wrote earlier, after removing variable from XML and binding from MainActivity error disappears.
I know it is a lot of code, so if something is redundant just let me know. There is factory class still missing, but I will post it if it's necessary. Also MainRepo is one I haven't attached here, but it's quite long, but I can post it all if you're gonna need it.
Here is the problem --> android:text="#{() -> viewmodel.pageNumber}"
correct syntax for assigning value using dataBinding is
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:layout_centerInParent="true"
android:text="#{viewmodel.pageNumber}"/>

Categories

Resources