Android studio cant find my specific binding - kotlin

Im trying to implement databinding into my app. For some reason, android studio finds a generic "viewdatabinding" instead of my ActivityMainBinding.
this is my mainactivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}
}
this is my activity_main.xml
<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:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<fragment
android:id="#+id/navigationFragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:navGraph="#navigation/navigation"
app:defaultNavHost="true"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</Layout>
and this is my gradle build file
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.android.gintastic"
minSdkVersion 19
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'
}
}
dataBinding{
enabled = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
the error im getting is the following:
Ive done this before for an other project and had no trouble doing so. Maybe its because its a different SDK version?

It is simple, you are not generating DataBinding class at all.
DataBinding xml should look like:
layout tag
-data tag
-other xml
close layout tag

The problem was i typed Layout instead of layout.
my bad

Related

Duplicate Class Error in kotlin gradle implementation

I get duplicate class errors as gradle implementation app's build.gradle file. But I don't know which implementation is actually a duplicate. How can i resolve this? Is there a better way like using bom for the dependencies?
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.bettehomes'
compileSdk 33
defaultConfig {
applicationId "com.example.bettehomes"
minSdk 25
targetSdk 33
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 {
// Import the Compose BOM
implementation 'com.google.android.gms:play-services-maps:18.1.0'
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.5.1'
implementation 'androidx.activity:activity-compose:1.7.0-alpha04'
implementation "androidx.compose.ui:ui-tooling:1.3.3"
implementation "androidx.compose.ui:ui-tooling-preview:1.3.3"
implementation 'androidx.compose.material3:material3:1.1.0-alpha04'
// Android Studio Preview Support
debugImplementation "androidx.compose.ui:ui-tooling:1.3.3"
//testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.4.0-alpha05"
debugImplementation "androidx.compose.ui:ui-test-manifest:1.3.3"
}
I had this issue today and used gradle dependencies to figure out the dependency tree
I figured out that a lib used a latest version of appcompat which used kotlin 1.8.0, a version that has this issue.
In my case the fix was to add the kotlinVersion manually:
buildscript {
ext {
buildToolsVersion = "32.0.0"
minSdkVersion = 21
compileSdkVersion = 33
targetSdkVersion = 32
androidXBrowser = "1.4.0"
kotlinVersion = "1.8.0"
}
...
}
For more information check this issue: https://github.com/proyecto26/react-native-inappbrowser/issues/398

I'm trying to get stock prices from Yahoo Finance API, getting an java.io.FileNotFoundException

I'm trying to get stock prices from Yahoo Finance,
but I'm getting an error. This was the code I wrote before, and it worked well before, but after a long time, it doesn't work, returning the following error code.
java.io.FileNotFoundException while trying to execute YahooFinance.get operation
I found a question similar to my problem, and I tried to update Java according to the comments to correct the Java version,but the problem was not resolved.
When I click the URL given with the error code, it seems to get the data from Yahoo Finance, but it doesn't work programmatically.
package com.jym.yftest
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.jym.yftest.databinding.ActivityMainBinding
import yahoofinance.YahooFinance
class MainActivity : AppCompatActivity() {
private val vBinding by lazy { ActivityMainBinding.inflate(layoutInflater)}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(vBinding.root)
vBinding.testBtn.setOnClickListener {
Thread(Runnable {
try{
val stock = YahooFinance.get("APL")
Log.d("test", stock.toString())
}catch(err:Exception){
Log.d("test", err.toString())
}
this#MainActivity.runOnUiThread(java.lang.Runnable {
})
}).start()
}
}
}
build.gradle(module)
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 33
defaultConfig {
applicationId "com.jym.yftest"
minSdk 22
targetSdk 33
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'
buildFeatures{
viewBinding true
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
}
build.gradle(project)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

kotlin:Internal Error occurred while analyzing this expression

I am using navigation safeargs for passing arguments from one Fragment to another .
However , after I rebuild the project ,I could not parse the augument I had sent .I got an error below:
Internal Error occurred while analyzing this expression:
org.jetbrains.kotlin.descriptors.InvalidModuleException: Accessing invalid module descriptor <production sources for module FavDishKT.app> is a module[ModuleDescriptorImpl#10578057]
at org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl.assertValid(ModuleDescriptorImpl.kt:62)
at org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl.getPackage(ModuleDescriptorImpl.kt:84)
at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory.createScopesForFile(FileScopeFactory.kt:62)
at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory.createScopesForFile$default(FileScopeFactory.kt:61)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl$cache$1.invoke(FileScopeProvider.kt:48)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl$cache$1.invoke(FileScopeProvider.kt:46)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:578)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:651)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl.getFileScopes(FileScopeProvider.kt:53)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProvider$DefaultImpls.getFileResolutionScope(FileScopeProvider.kt:30)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl.getFileResolutionScope(FileScopeProvider.kt:40)
at org.jetbrains.kotlin.resolve.lazy.DeclarationScopeProviderImpl.getResolutionScopeForDeclaration(DeclarationScopeProviderImpl.java:60)
at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.getOuterScope(LazyClassDescriptor.java:353)
at org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport$scopeForClassHeaderResolution$1.invoke(ClassResolutionScopesSupport.kt:44)
at org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport$scopeForClassHeaderResolution$1.invoke(ClassResolutionScopesSupport.kt:43)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageM...
My configures:
build.gradle(project:FavDishKT)
// 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.2"
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
}
**build.gradle(Module:FavDishKT.app)**
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
// For more details visit https://developer.android.com/guide/navigation/navigation-pass-data#Safe-args
id 'androidx.navigation.safeargs.kotlin'
id 'kotlin-parcelize'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.gearsrun.favdishkt"
minSdkVersion 21
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
}
packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.5'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation("androidx.recyclerview:recyclerview:1.2.1")
// For control over item selection of both touch and mouse driven selection
implementation("androidx.recyclerview:recyclerview-selection:1.1.0")
implementation 'com.airbnb.android:lottie:3.4.1'
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation("com.squareup.okhttp3:okhttp:4.9.0")
implementation("com.squareup.okhttp3:logging-interceptor:4.9.0")
implementation 'com.google.code.gson:gson:2.8.7'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
}
dependencies {
//room
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
}
My idea is to pass the dish item from the homepage to another details page ,as follow ,Therefor ,I will need to pass a entity which names :FavDish
FavDish entity:
#Parcelize
#Entity(tableName = "fav_dishes_table")
data class FavDish(
#PrimaryKey(autoGenerate = true) val id:Int = 0,
#ColumnInfo val image:String,
#ColumnInfo(name = "image_source")val imageSource:String,
#ColumnInfo val title:String,
#ColumnInfo val type:String,
#ColumnInfo val category:String,
#ColumnInfo val ingredients:String,
#ColumnInfo(name = "cooking_time") val cookingTime:String,
#ColumnInfo(name = "instructions") val directionToCook:String,
#ColumnInfo(name = "favorite_dish") var favoriteDish:Boolean = false,
):Parcelable
And then , I have modified the navigation.xml ,from the AllDishes page to the DishDetailsFragment , and pass the entity reference as aguments :
<?xml version="1.0" encoding="utf-8"?>
<navigation 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"
android:id="#+id/mobile_navigation"
app:startDestination="#+id/navigation_all_dishes">
<fragment
android:id="#+id/navigation_all_dishes"
android:name="com.gearsrun.favdishkt.view.fragments.AllDishesFragment"
android:label="Home"
tools:layout="#layout/fragment_all_dishes" >
<action
android:id="#+id/action_navigation_all_dishes_to_dishDetailsFragment"
app:destination="#id/dishDetailsFragment" />
</fragment>
<fragment
android:id="#+id/navigation_favorite_dishes"
android:name="com.gearsrun.favdishkt.view.fragments.FavoriteFragment"
android:label="Favorite"
tools:layout="#layout/fragment_favorite_dishes" >
<action
android:id="#+id/action_navigation_favorite_dishes_to_dishDetailsFragment"
app:destination="#id/dishDetailsFragment" />
</fragment>
<fragment
android:id="#+id/navigation_random_dish"
android:name="com.gearsrun.favdishkt.view.fragments.RandomFragment"
android:label="Random"
tools:layout="#layout/fragment_random_dish" />
<fragment
android:id="#+id/dishDetailsFragment"
android:name="com.gearsrun.favdishkt.view.fragments.DishDetailsFragment"
android:label="fragment_dish_details"
tools:layout="#layout/fragment_dish_details" >
<argument
android:name="dishDetails"
app:argType="com.gearsrun.favdishkt.model.entities.FavDish"/>
</fragment>
</navigation>
From my AllDishsFragment (home page ) ,I use findNavController,and navigate to the detailsDishFragment ,and pass the entity to it :
class AllDishesFragment : Fragment(){
private var _binding: FragmentAllDishesBinding? = null
private val binding get() = _binding!!
private val mFavDishViewModel :FavDishViewModel by viewModels{
FavDishViewModelFactory((requireActivity().application as FavDishApplication).repository)
}
private lateinit var mFavDishAdapter: FavDishAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentAllDishesBinding.inflate(inflater, container, false)
val root: View = binding.root
binding.imgAddHome.setOnClickListener {
val intent = Intent(context,AddUpdateActivity::class.java)
startActivity(intent)
}
binding.rvHome.layoutManager = GridLayoutManager(requireActivity(),2)
mFavDishAdapter = FavDishAdapter(this)
binding.rvHome.adapter = mFavDishAdapter
mFavDishViewModel.allDishesList.observe(viewLifecycleOwner){dishes->
dishes.let{
if(it.isNotEmpty()){
binding.rvHome.visibility=View.VISIBLE
binding.txtNotice.visibility=View.GONE
mFavDishAdapter.getAllDishes(it)
}else{
binding.rvHome.visibility =View.GONE
binding.txtNotice.visibility=View.VISIBLE
}
}
}
return root
}
fun dishDetails(favDish: FavDish){
if(requireActivity() is MainActivity){
(activity as MainActivity?)!!.hideBottomNavigationView()
}
findNavController().navigate(AllDishesFragmentDirections.actionNavigationAllDishesToDishDetailsFragment(favDish))
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
And the DetailDishFragment ,where it should receive the args and parse it occured the error :
class DishDetailsFragment : Fragment() {
private val mFavDishViewModel : FavDishViewModel by viewModels{
FavDishViewModelFactory((requireActivity().application as FavDishApplication).repository)
}
private var mBinding : FragmentDishDetailsBinding? =null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mBinding = FragmentDishDetailsBinding.inflate(inflater,container,false)
return mBinding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val args:DishDetailsFragmentArgs by navArgs()
args.let{
try {
Glide.with(requireActivity())
.load(it.dishDetails.image)
}catch(e: IOException){
}
}
}
}
And the problem description :
Internal Error occurred while analyzing this expression:
org.jetbrains.kotlin.descriptors.InvalidModuleException: Accessing invalid module descriptor <production sources for module FavDishKT.app> is a module[ModuleDescriptorImpl#10578057]
at org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl.assertValid(ModuleDescriptorImpl.kt:62)
at org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl.getPackage(ModuleDescriptorImpl.kt:84)
at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory.createScopesForFile(FileScopeFactory.kt:62)
at org.jetbrains.kotlin.resolve.lazy.FileScopeFactory.createScopesForFile$default(FileScopeFactory.kt:61)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl$cache$1.invoke(FileScopeProvider.kt:48)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl$cache$1.invoke(FileScopeProvider.kt:46)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:578)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:651)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl.getFileScopes(FileScopeProvider.kt:53)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProvider$DefaultImpls.getFileResolutionScope(FileScopeProvider.kt:30)
at org.jetbrains.kotlin.resolve.lazy.FileScopeProviderImpl.getFileResolutionScope(FileScopeProvider.kt:40)
at org.jetbrains.kotlin.resolve.lazy.DeclarationScopeProviderImpl.getResolutionScopeForDeclaration(DeclarationScopeProviderImpl.java:60)
at org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.getOuterScope(LazyClassDescriptor.java:353)
at org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport$scopeForClassHeaderResolution$1.invoke(ClassResolutionScopesSupport.kt:44)
at org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport$scopeForClassHeaderResolution$1.invoke(ClassResolutionScopesSupport.kt:43)
at org.jetbrains.kotlin.storage.LockBasedStorageManager$LockBasedLazyValue.invoke(LockBasedStorageM...
Could anyone helps ?Thank you so much in advance !!
install and uninstall kotlin plugin.it Worked for me
For My case, I had the same issue but it was only happening in one particular project, The rest were okay so I tried upgrading the build Gradle plugin of the specific project to 7.3.0 and It worked. You can try to see if this helps
Invalid Cache Restart with both vcs and system cache option selected can resolved this issue. It worked for me.
Update: These warnings frequently coming in Dolphin Version of Android Studio(stable) causing faliure of auto suggestion and layout rendering. If you want to get rid of them for stable version you can use Chipmunk version or try canary channels of dolphin.
Updating ktx implementation and syncing gradle worked for me!

RecyclerView and DataBinding

i try to build a sample app using the navigation drawer activitiy and a listview in one of the sub fragments. Therefor i created the project and then added a list fragment to res.layout.navigation.mobile_navigation.
So far so nice. When compiling in ItemRecyclerViewAdapter the following error occurs:
import com.example.mydatabindingtest.databinding.FragmentItemBindingImpl;
^
symbol: class FragmentItemBindingImpl
location: package com.example.mydatabindingtest.databinding
After reading a lot i suppose this file should be generates automatically when creating the app. So the question is why is the file not created. Or if i'm wrong how should the file look like.
I'm using:
Android Studio 4.2
Gradle 4.2.0
Kotlin 1.5.0
All kept up to date by updating when prompted.
Here the code snippets i think you need to help:
build.gradle(:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.mydatabindingtest"
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'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
dataBinding true
viewBinding true
}
}
fragment_item.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data class="FragmentItemBinding">
<variable
name="item"
type="com.example.mydatabindingtest.ui.listview.placeholder.PlaceholderContent.PlaceholderItem" />
</data>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/item_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"
android:text="#{item.id}"/>
<TextView
android:id="#+id/content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/text_margin"
android:textAppearance="?attr/textAppearanceListItem"
android:text="#{item.content}"/>
</LinearLayout>
</layout>
MyItemRecyclerViewAdapter.kt
package com.example.mydatabindingtest.ui.listview
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.mydatabindingtest.R
import com.example.mydatabindingtest.ui.listview.placeholder.PlaceholderContent.PlaceholderItem
import com.example.mydatabindingtest.ui.listview.databinding.FragmentItemBinding
/**
* [RecyclerView.Adapter] that can display a [PlaceholderItem].
* TODO: Replace the implementation with code for your data type.
*/
class MyItemRecyclerViewAdapter(
private val values: List<PlaceholderItem>
) : RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
FragmentItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = values[position]
holder.idView.text = item.id
holder.contentView.text = item.content
}
override fun getItemCount(): Int = values.size
inner class ViewHolder(binding: FragmentItemBinding) : RecyclerView.ViewHolder(binding.root) {
val idView: TextView = binding.itemNumber
val contentView: TextView = binding.content
override fun toString(): String {
return super.toString() + " '" + contentView.text + "'"
}
}
}
I appologize if the question is already answered. To defend my self, i did not find the answer after searching for several hours, since the answers i read are farly old and did not solve my problem.
So your help will be apreciated.
Best regards
EDIT:
After domicoders question, i rebuilt the hole project. Now the three following errors are shown:
e: G:\Projekte\Android\MyDataBindingTest\app\src\main\java\com\example\mydatabindingtest\ui\listview\MyItemRecyclerViewAdapter.kt: (11, 50): Unresolved reference: databinding
e: G:\Projekte\Android\MyDataBindingTest\app\src\main\java\com\example\mydatabindingtest\ui\listview\MyItemRecyclerViewAdapter.kt: (24, 13): Unresolved reference: FragmentItemBinding
e: G:\Projekte\Android\MyDataBindingTest\app\src\main\java\com\example\mydatabindingtest\ui\listview\MyItemRecyclerViewAdapter.kt: (41, 37): Unresolved reference: FragmentItemBinding
The reason for these messages is that the required class is not existing. But why does android studio insert the questionable import when the file is not created automatically. Or am i mistanken at some point?
Best regards
As stated here, enable databinding in your App Level build.gradle file
android {
...
dataBinding{
enabled=true
}
}

How to fix databinding errors in kotlin?

I'm having an online Kotlin course. When I tried to apply the data binding part, I had some red errors in the .kt file.
The ActivityMainBinding is not imported so I did that manually,but the problem still persists.
here is the .kt :
package com.example.aboutme
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import com.example.android.aboutme.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
findViewById<Button>(R.id.Done_button).setOnClickListener { addNickname(it) }
}
private fun addNickname(view: View) {
val editText = findViewById<EditText>(R.id.nickname_editText)
val nicknameText = findViewById<TextView>(R.id.nickname_text)
nicknameText.text = editText.text
editText.visibility = View.GONE
view.visibility = View.GONE
nicknameText.visibility = View.VISIBLE
//Hide the keyboard
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
}
and here is the .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"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingStart="#dimen/padding"
android:paddingEnd="#dimen/padding">
<TextView
android:text="#string/hanan_tabak"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/name_text"
android:textAlignment="center" style="#style/name_style"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/nickname_editText" style="#style/name_style" android:hint="#string/what_is_your_nickname"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/nickname_text" style="#style/name_style"
android:layout_gravity="center_horizontal" android:visibility="gone"/>
<Button
android:text="#string/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/Done_button"
android:layout_gravity="center_horizontal"
style="#style/Widget.AppCompat.Button.Colored"/>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content" app:srcCompat="#android:drawable/btn_star_big_on"
android:id="#+id/star_image" android:contentDescription="#string/yellow_star" android:padding="8dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="#string/bio"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/scroll_text" style="#style/name_style"
android:lineSpacingMultiplier="1.2"/>
</ScrollView>
</LinearLayout>
</Layout>
and here is the gradle.app:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.0"
defaultConfig {
applicationId "com.example.aboutme"
minSdkVersion 19
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'
}
}
dataBinding { enabled = true}
}
dependencies {
kapt "com.android.databinding:compiler:3.4.1"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
and here is gradle.project:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.31'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
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()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
The errors I face are:
1- In the line of code:
import com.example.android.aboutme.databinding.ActivityMainBinding :
(android) is in red font and the error is (Unresolved reference:android)
2- In this line of code:
private lateinit var binding: ActivityMainBinding :
(ActivityMainBinding) is in red font and the error is ( Unresolved reference AcitivityMainBinding)
3- In this line of code:
binding = DataBindingUtil.setContentView(this, R.layout.activity_main):
there is a red underline under setContentView and the error says (Not enough information to infer variable T)
I got the same error and turned out it was a typo in my import.
But I can see that is not the case with your issue.
Although when I was searching for the answers I came across a question identical to yours asked by someone else. He apparently solved it by cleaning and rebuilding the project.
To do that go to Build -> Clean Project and then after that, Build -> Rebuild Project
Hope it works out!
Here's the link to the other question if you want to check
I solved this issue in Android Studio with the invalidate cache and restart option in file menu
Wrap your layout in this
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- YOUR LAYOUT HERE -->
</layout>
if still not working.
you can set viewbinding files in ' /build/generate/xxx ' as sources dir.
it is work for me.
I also faced this problem. The proper way to solve is to put this in build.gradle app.buildFeatures{ dataBinding = true viewBinding = true }