java.lang.IllegalStateException :ViewTreeLifecycleOwner not found from DecorView#5ab7e30[MainActivity] - kotlin

i followed this documentation for including a ComposeView directly inside a fragment without xml layout inflating , but it giving java.lang.IllegalStateException.
please help me to fix this issue.
Android Studio: 2020.3.1 canary 14
compose_version :'1.0.0-beta01'
this is Fragment's code:
class RecipeListFragment : Fragment() {
private lateinit var viewModel: RecipeListViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setContent {
Column(
modifier = Modifier
.padding(16.dp)
) {
Text(
text = "Recipe List",
style = MaterialTheme.typography.h3
)
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this).get(RecipeListViewModel::class.java)
}
}
this is run time error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mvvmrecepiapp, PID: 18722
java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from DecorView#5ab7e30[MainActivity]
at androidx.compose.ui.platform.WindowRecomposer_androidKt.createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:214)
at androidx.compose.ui.platform.WindowRecomposer_androidKt.access$createLifecycleAwareViewTreeRecomposer(WindowRecomposer.android.kt:1)
at androidx.compose.ui.platform.WindowRecomposerFactory$Companion$LifecycleAware$1.createRecomposer(WindowRecomposer.android.kt:97)
at androidx.compose.ui.platform.WindowRecomposerPolicy.createAndInstallWindowRecomposer$ui_release(WindowRecomposer.android.kt:152)
at androidx.compose.ui.platform.WindowRecomposer_androidKt.getWindowRecomposer(WindowRecomposer.android.kt:200)
at androidx.compose.ui.platform.AbstractComposeView.ensureCompositionCreated(ComposeView.android.kt:200)
at androidx.compose.ui.platform.AbstractComposeView.onAttachedToWindow(ComposeView.android.kt:235)
at android.view.View.dispatchAttachedToWindow(View.java:19553)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3430)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:3437)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2028)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1721)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7598)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:966)
at android.view.Choreographer.doCallbacks(Choreographer.java:790)
at android.view.Choreographer.doFrame(Choreographer.java:725)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:951)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
UPDATE:
here is my build.gradle(:app)
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.example.mvvmrecepiapp"
minSdk 21
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'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.4.32'
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'com.google.android.material:material:1.3.0'
// compose_version = "1.0.0-beta01" variable in project level build.gradle
implementation "androidx.compose.ui:ui:$compose_version"
implementation "androidx.compose.material:material:$compose_version"
implementation "androidx.compose.ui:ui-tooling:$compose_version"
implementation 'androidx.activity:activity-compose:1.3.0-alpha06'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
def fragment_version = "1.3.2"
implementation "androidx.fragment:fragment-ktx:$fragment_version"
def nav_version = "2.3.5"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.0.0-beta04"
}

The support for ViewTreeLifecycleOwner was introduced in the AppCompat with the version 1.3.0.
Currently the latest AppCompat release is
implementation 'androidx.appcompat:appcompat:1.3.0'

Related

android Jetpack Room Export schemas failed

I refer to setting Export schemas in the documentation, But it failed, the error is as follows:
The following is my Gradle configuration:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
// hilt
id 'kotlin-kapt'
id 'com.google.dagger.hilt.android'
}
android {
namespace 'com.freedom.android'
compileSdk 32
defaultConfig {
applicationId "com.freedom.android"
minSdk 26
targetSdk 32
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
// Room
javaCompileOptions {
annotationProcessorOptions {
compilerArgumentProviders(
new RoomSchemaArgProvider(new File(projectDir, "schemas"))
)
}
}
}
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 '1.1.1'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
applicationVariants.all { variant ->
variant.getRuntimeConfiguration().exclude group: 'com.google.code.findbugs', module: 'jsr305'
}
}
dependencies {
/**
* Room
*/
def room_version = "2.4.3"
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 Coroutine features, you must add `ktx` artifact from Room as a dependency. androidx.room:room-ktx:<version>
implementation "androidx.room:room-ktx:$room_version"
// Could not find method ksp() for arguments [androidx.room:room-compiler:2.4.3] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
// To use Kotlin Symbol Processing (KSP)
// ksp "androidx.room:room-compiler:$room_version"
// hilt
implementation("com.google.dagger:hilt-android:2.44")
kapt("com.google.dagger:hilt-android-compiler:2.44")
def lifecycle_viewmodel_version = "2.5.1"
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_viewmodel_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_viewmodel_version"
// private val articleViewModel: ArticleViewModel by viewModels()
// java.lang.IllegalArgumentException: CreationExtras must have a value by `SAVED_STATE_REGISTRY_OWNER_KEY`
implementation "androidx.fragment:fragment-ktx:1.5.1"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.1'
implementation "androidx.compose.ui:ui:$compose_ui_version"
implementation "androidx.compose.ui:ui-tooling-preview:$compose_ui_version"
implementation 'androidx.compose.material:material:1.1.1'
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_ui_version"
debugImplementation "androidx.compose.ui:ui-tooling:$compose_ui_version"
debugImplementation "androidx.compose.ui:ui-test-manifest:$compose_ui_version"
}
// hilt
// Allow references to generated code
kapt {
correctErrorTypes = true
}
// Room
class RoomSchemaArgProvider implements CommandLineArgumentProvider {
#InputDirectory
#PathSensitive(PathSensitivity.RELATIVE)
File schemaDir
RoomSchemaArgProvider(File schemaDir) {
this.schemaDir = schemaDir
}
#Override
Iterable<String> asArguments() {
// Note: If you're using KSP, you should change the line below to return
// ["room.schemaLocation=${schemaDir.path}"]
return ["-Aroom.schemaLocation=${schemaDir.path}"]
}
}
I am basically sure that it is an error caused by setting Export schemas. When I set exportSchema = false, the program can run normally. Sorry my settings file is a bit messy, but like I said, it works.
Convert string like this:
return ["-Aroom.schemaLocation=${schemaDir.path}".toString()]
About bug here:
https://github.com/gradle/gradle/issues/4730#

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
}

Jetpack Compose - unresolved refence when using viewmodel value in LazyColumn

For my college project I want to use data from Firestore, and then use MVVM pattern to display the items on the Lazy Column.
Here is the code of the screen of where I want the values of viewmodel to be displayed:
fun HomeScreen (navController: NavController, viewModel: ArticleViewModel = hiltViewModel()){
var expanded = remember { mutableStateOf(false) }
val articleResponse = viewModel.articleState.value
Scaffold() {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
items(items = articleResponse.data) {
ArticleList(model = it) { model ->
Log.d("TAG", "Clicked on $model")
navController.navigate(route = NavScreens.DetailScreen.name +"/$model")
}
}
}
}
}
Here is the field of where exactly I get the error that is I mentioned in the title:
here
Previously I used an array to display the item in the LazyColumn and it worked normally.
Perhaps, the problem lies in the ViewModel? Here is the ViewModel that I'm using:
#HiltViewModel
class ArticleViewModel #Inject constructor(
private val useCases: UseCases
):ViewModel() {
private val _articleState = mutableStateOf<Response<List<Article>>>(Response.Loading)
val articleState: State<Response<List<Article>>> = _articleState
init {
getArticles()
}
private fun getArticles() {
viewModelScope.launch {
useCases.getArticle().collect { response ->
_articleState.value = response
}
}
}
}
When I tried searching for the solution, I've read that the problem could be with the dependencies/plugins, I have tried changing couple of the dependencies but the issue still persists. I've heard that some of the plugins doesn't work with others since I'm new to jetpack compose it is harder for me to identify the issues within the dependencies.
Here is my Gradle files:
buildscript {
ext {
compose_version = '1.0.1'
hilt_version = "2.40.5"
gradle_version = "7.2.0"
kotlin_version = "1.6.20"
coroutines_version = "1.6.1"
google_services_version = "4.3.10"
hilt_version = "2.40.5"
core_version = "1.7.0"
appcompat_version = "1.4.1"
live_data_version = "2.4.1"
activity_compose_version = "1.4.0"
material_version = "1.6.0"
hilt_navigation_compose_version = "1.0.0"
firebase_bom_version = "30.0.0"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.google.gms:google-services:4.3.4'
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
classpath "com.android.tools.build:gradle:$gradle_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.gms:google-services:$google_services_version"
}
}// Top-level build file where you can add configuration options common to all sub-projects/modules.
plugins {
id 'com.android.application' version '7.1.3' apply false
id 'com.android.library' version '7.1.3' apply false
id 'org.jetbrains.kotlin.android' version '1.5.21' apply false
}
task clean(type: Delete) {
delete rootProject.buildDir
}
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'com.google.gms.google-services'
id 'dagger.hilt.android.plugin'
id 'kotlin-kapt'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.flow"
minSdk 28
targetSdk 31
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
kotlinCompilerVersion '1.5.21'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
implementation "androidx.compose.compiler:compiler:1.0.0-beta08"
implementation 'androidx.core:core-ktx:1.7.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.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.activity:activity-compose:1.3.0-alpha02'
implementation "androidx.appcompat:appcompat:$appcompat_version"
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
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"
implementation "androidx.core:core-splashscreen:1.0.0-beta02"
implementation "androidx.navigation:navigation-compose:2.4.0-alpha10"
implementation("io.coil-kt:coil-compose:2.1.0")
implementation "com.google.firebase:firebase-firestore:22.0.1"
implementation "com.google.dagger:hilt-android:$hilt_version"
implementation platform("com.google.firebase:firebase-bom:$firebase_bom_version")
implementation "com.google.firebase:firebase-firestore-ktx"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
kapt "androidx.hilt:hilt-compiler:1.0.0"
implementation "androidx.hilt:hilt-navigation-compose:$hilt_navigation_compose_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:$coroutines_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$live_data_version"
}
I would be grateful if you are able to assist me on finding the solution.
The problem is that articleState.value is Response not List. You can do something like that:
val articleResponse = viewModel.articleState.value
when (articleResponse) {
Response.Loading -> <LoadingComponenet />
Response.Error -> <ErrorComponent />
Response.Success -> Scaffold() {
.............
}
}

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!

DaggerAppComponent has unresolved referance in kotlin

Please, help me. I have tried out all ways to solve this problem, but no result :( More information about my app
build.gradle(Module:app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'
apply plugin: 'kotlin-kapt'
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
// You can find the lastest version number here:
https://docs.fabric.io/android/changelog.html#fabric-gradle-plugin
classpath 'io.fabric.tools:gradle:1.+'
}
}
project.ext {
supportLibraryVersion = "26.1.0"
androidArchVersion = "1.0.0-rc1"
daggerVersion = "2.11"
butterKnifeVersion = "8.7.0"
rxJavaVersion = "2.1.0"
rxAndroidVersion = "2.0.1"
timberVersion = "4.5.1"
priorityJobQueueVersion = "2.0.1"
playServicesVersion = "11.4.2"
retrofitVersion = "2.1.0"
okHttpVersion = "3.4.1"
rxRelayVersion = "2.0.0"
rxLintVersion = "1.6"
}
android {
compileSdkVersion 27
defaultConfig {
javaCompileOptions.annotationProcessorOptions.includeCompileClasspath =
true
vectorDrawables.useSupportLibrary true
applicationId "***"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
resConfigs "en"
testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
splits {
density {
enable true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
debug {
// Disable fabric build ID generation for debug builds
ext.enableCrashlytics = false
}
}
}
kapt {
generateStubs = true
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'uk.co.chrisjenx:calligraphy:2.2.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.android.support:design:27.0.2'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
implementation('com.crashlytics.sdk.android:crashlytics:2.9.0#aar') {
transitive = true
}
implementation 'com.android.support:support-v4:27.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-
core:3.0.1'
implementation "com.android.support:appcompat-
v7:$project.supportLibraryVersion"
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
// GSON Converter
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
//OkHttp Logging Interceptor
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'
implementation 'com.google.code.gson:gson:2.8.2'
// ReactiveX
implementation "io.reactivex.rxjava2:rxjava:$project.rxJavaVersion"
implementation
"io.reactivex.rxjava2:rxandroid:$project.rxAndroidVersion"
//Room database
implementation "android.arch.persistence.room:runtime:1.1.1"
implementation "android.arch.persistence.room:rxjava2:1.1.1"
kapt "android.arch.persistence.room:compiler:1.1.1"
implementation "android.arch.paging:runtime:1.0.0-alpha3"
// Lifecycle
implementation
"android.arch.lifecycle:runtime:$project.androidArchVersion"
implementation
"android.arch.lifecycle:extensions:$project.androidArchVersion"
annotationProcessor
"android.arch.lifecycle:compiler:$project.androidArchVersion"
// RxRelay
implementation
"com.jakewharton.rxrelay2:rxrelay:$project.rxRelayVersion"
// RxLint
implementation "nl.littlerobots.rxlint:rxlint:$project.rxLintVersion"
// GCM Network Manager
implementation "com.google.android.gms:play-services-
gcm:$project.playServicesVersion"
// Priority Job Queue
implementation "com.birbit:android-priority-
jobqueue:$project.priorityJobQueueVersion"
// ButterKnife
implementation "com.jakewharton:butterknife:$project.butterKnifeVersion"
annotationProcessor "com.jakewharton:butterknife-
compiler:$project.butterKnifeVersion"
// Dagger
def daggerVer = 2.14
implementation "com.google.dagger:dagger:$daggerVer"
implementation "com.google.dagger:dagger-android-support:$daggerVer"
kapt "com.google.dagger:dagger-android-processor:$daggerVer"
kapt "com.google.dagger:dagger-compiler:$daggerVer"
// Timber
implementation "com.jakewharton.timber:timber:$project.timberVersion"
}
Here is my App, where DaggerAppComponent is red
class App : Application(), HasActivityInjector {
#Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity>
override fun onCreate() {
super.onCreate()
if (BuildConfig.DEBUG) {
Timber.plant(Timber.DebugTree())
}
DaggerAppComponent
.builder()
.application(this)
.build()
.inject(this)
JobManagerFactory().getJobManager(this)
}
override fun activityInjector(): AndroidInjector<Activity> {
return this.dispatchingAndroidInjector
}
}
Android Studio Version - 3.0.1
I have registered app in the Manifest and have rebuild and invalidated caches more times.
Don't understand what is the problem. Please, save me :(