my android instromented tests have no results - android

I am trying to run instrumented tests for my fragments and appears nothing works
the result shows nothing no pass no errors nothing
like this answer :answer link
I tried unchecking the run instrumented test with Gradle
put the result is nothing :
tests result
and when checking it : throws exception
"Run Android instrumented tests using Gradle" option was ignored because this module type is not supported yet.
"
and yet no results
test results2
my project gradle:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlinVersion = '1.3.72'
ext.navigationVersion = '2.4.1'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion"
// 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
}
ext {
// Sdk and tools
// Support library and architecture components support minSdk 14 and above.
minSdkVersion = 21
targetSdkVersion = 30
compileSdkVersion = 31
// App dependencies
androidXVersion = '1.0.0'
androidXAnnotations = '1.0.1'
androidXLegacySupport = '1.0.0'
appCompatVersion = '1.2.0'
archLifecycleVersion = '2.2.0'
cardVersion = '1.0.0'
materialVersion = '1.1.0'
fragmentVersion = '1.1.0-alpha07'
recyclerViewVersion = '1.1.0'
mockitoVersion = '2.8.9'
constraintVersion = '2.0.0-rc1'
dexMakerVersion = '2.12.1'
coroutinesVersion = '1.2.1'
roomVersion = '2.4.2'
koinVersion = '2.0.1'
truthVersion = '0.44'
junitVersion = '4.12'
androidXTestCoreVersion = '1.2.0-beta01'
robolectricVersion = '4.3-beta-1'
androidXTestExtKotlinRunnerVersion = '1.1.1'
archTestingVersion = '2.0.0'
playServicesVersion = '17.0.0'
hamcrestVersion = '1.3'
androidXTestRulesVersion = '1.2.0-beta01'
espressoVersion = '3.2.0'
}
app gradle:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
apply plugin: "androidx.navigation.safeargs.kotlin"
android {
compileSdkVersion rootProject.compileSdkVersion
defaultConfig {
applicationId "com.mostafan3ma.android.pcm_helper10"
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode 1
versionName "1.1"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
kotlinOptions {
jvmTarget = "1.8"
}
testOptions.unitTests {
includeAndroidResources = true
returnDefaultValues = true
}
buildFeatures {
viewBinding = true
dataBinding = true
}
}
dependencies {
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation "com.google.android.material:material:$materialVersion"
implementation "androidx.constraintlayout:constraintlayout:$constraintVersion"
implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation "androidx.annotation:annotation:$androidXAnnotations"
kapt "androidx.lifecycle:lifecycle-compiler:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$archLifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$archLifecycleVersion"
//Room dependencies
implementation("androidx.room:room-runtime:$roomVersion")
annotationProcessor("androidx.room:room-compiler:$roomVersion")
kapt("androidx.room:room-compiler:$roomVersion")
implementation("androidx.room:room-ktx:$roomVersion")
implementation 'com.google.code.gson:gson:2.8.6'
implementation "com.google.android.gms:play-services-location:$playServicesVersion"
implementation "com.google.android.gms:play-services-maps:$playServicesVersion"
//floating action button
implementation 'com.getbase:floatingactionbutton:1.10.1'
//xls files api
implementation 'org.apache.poi:poi:3.17'
// Dependencies for local unit tests
testImplementation "junit:junit:$junitVersion"
testImplementation "androidx.test:core-ktx:$androidXTestCoreVersion"
testImplementation "org.hamcrest:hamcrest-all:$hamcrestVersion"
// Dependencies for Android instrumented unit tests
androidTestImplementation "junit:junit:$junitVersion"
androidTestImplementation "org.mockito:mockito-core:$mockitoVersion"
androidTestImplementation "com.linkedin.dexmaker:dexmaker-mockito:$dexMakerVersion"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
androidTestImplementation "androidx.arch.core:core-testing:$archTestingVersion"
//Robolectric and AndroidX test Dependencies
testImplementation "androidx.test:core-ktx:$androidXTestCoreVersion"
testImplementation "org.robolectric:robolectric:$robolectricVersion"
"androidx.test.ext:junit-ktx:$androidXTestExtKotlinRunnerVersion"
testImplementation "androidx.arch.core:core-testing:$archTestingVersion"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$coroutinesVersion"
// AndroidX Test - Instrumented testing
androidTestImplementation "androidx.test.ext:junit:$androidXTestExtKotlinRunnerVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
androidTestImplementation "androidx.test.espresso:espresso-contrib:$espressoVersion"
implementation "androidx.test.espresso:espresso-idling-resource:$espressoVersion"
implementation "androidx.fragment:fragment-testing:$fragmentVersion"
implementation "androidx.test:core:$androidXTestCoreVersion"
}
I am using ServiceLocater to inject repository into fragments
ServiceLocater.kt:
package com.mostafan3ma.android.pcm_helper10
import android.content.Context
import androidx.annotation.VisibleForTesting
import androidx.room.Room
import com.mostafan3ma.android.pcm_helper10.data.source.DefaultLocalDataSource
import com.mostafan3ma.android.pcm_helper10.data.source.LocalDataSource.LocalDataSource
import com.mostafan3ma.android.pcm_helper10.data.source.PipeLinesRepository
import com.mostafan3ma.android.pcm_helper10.data.source.database.LineDataBase
import kotlinx.coroutines.runBlocking
object ServiceLocator {
private var dataBase:LineDataBase?=null
#Volatile
var pipeLinesRepository: PipeLinesRepository?=null
#VisibleForTesting set
private val lock=Any()
fun provideRepository(context: Context):PipeLinesRepository{
synchronized(this){
return pipeLinesRepository?:createPipeLineRepository(context)
}
}
private fun createPipeLineRepository(context: Context): PipeLinesRepository {
val newRepo=PipeLinesRepository(createLocalDataSource(context))
pipeLinesRepository=newRepo
return newRepo
}
private fun createLocalDataSource(context: Context): DefaultLocalDataSource {
val dataBase= dataBase?:createDatabase(context)
return LocalDataSource(dataBase.lineDao())
}
private fun createDatabase(context: Context): LineDataBase {
val result= Room.databaseBuilder(
context.applicationContext,
LineDataBase::class.java,
"Lins"
).fallbackToDestructiveMigration().build()
dataBase=result
return result
}
#VisibleForTesting
fun resetRepo(){
synchronized(lock){
runBlocking {
pipeLinesRepository?.clearAllLines()
}
dataBase?.apply {
clearAllTables()
close()
}
dataBase=null
pipeLinesRepository=null
}
}
}
and the test class for one of the fragments :
package com.mostafan3ma.android.pcm_helper10.lines
import android.os.Bundle
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.fragment.app.testing.launchFragmentInContainer
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.mostafan3ma.android.pcm_helper10.R
import com.mostafan3ma.android.pcm_helper10.ServiceLocator
import com.mostafan3ma.android.pcm_helper10.Utils.FakeDataSource
import com.mostafan3ma.android.pcm_helper10.Utils.MainCoroutineRule
import com.mostafan3ma.android.pcm_helper10.data.source.PipeLinesRepository
import com.mostafan3ma.android.pcm_helper10.data.source.database.DamagePoint
import com.mostafan3ma.android.pcm_helper10.data.source.database.PipeLine
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Assert.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
#MediumTest
#RunWith(AndroidJUnit4::class)
#ExperimentalCoroutinesApi
class MainLinesFragmentTest {
private val initList = mutableListOf<PipeLine>(
PipeLine(
id = 1,
name = "line1",
ogm = "1",
length = "1000",
type = "Water",
i_start = "1000",
i_end = "10",
start_point_x = "511511",
start_point_y = "3591511",
end_point_x = "511511",
end_point_y = "3591511",
start_work_date = "2/5/2022",
end_work_date = "3/5/2022",
work_team = "Mostafa Nema 1",
input = "1A",
extra_note = "note1",
points = mutableListOf<DamagePoint>(
DamagePoint(
no = 1, db = "11", depth = "1.1",
current1 = "111", current2 = "122",
gps_x = "511511", gps_y = "35911511",
note = "point note1", is_point = true
),
DamagePoint(
no = 2, db = "22", depth = "2.2",
current1 = "211", current2 = "222",
gps_x = "511511", gps_y = "35911511",
note = "point note2", is_point = true
),
DamagePoint(is_point = false),
DamagePoint(
no = 3, db = "33", depth = "3.1",
current1 = "311", current2 = "322",
gps_x = "511511", gps_y = "35911511",
note = "point note3", is_point = true
)
)
),
PipeLine(
id = 2,
name = "line2",
ogm = "2",
length = "2000",
type = "oil",
i_start = "2000",
i_end = "20",
start_point_x = "522522",
start_point_y = "3591522",
end_point_x = "522522",
end_point_y = "3591522",
start_work_date = "2/5/2022",
end_work_date = "3/5/2022",
work_team = "Mostafa Nema 2",
input = "2A",
extra_note = "note2",
points = mutableListOf<DamagePoint>(
DamagePoint(
no = 1, db = "11", depth = "1.1",
current1 = "111", current2 = "122",
gps_x = "511511", gps_y = "35911511",
note = "point note1", is_point = true
)
)
)
)
private lateinit var localDataSource: FakeDataSource
private lateinit var repository: PipeLinesRepository
#get:Rule
val mainCoroutineRule = MainCoroutineRule()
#get:Rule
var instantExecutorRule= InstantTaskExecutorRule()
#Before
fun setUp() {
localDataSource = FakeDataSource(initList)
repository=PipeLinesRepository(localDataSource,Dispatchers.Main)
ServiceLocator.pipeLinesRepository=repository
}
#After
fun tearDown() {
ServiceLocator.resetRepo()
}
#Test
fun displayFragment_TwoPipeInList()=mainCoroutineRule.runBlockingTest {
launchFragmentInContainer<MainLinesFragment>(Bundle(), R.style.Theme_Pcmhelper10)
onView(withId(R.id.fab_add_line)).check(matches(isDisplayed()))
}
}
and I got this exception which didn't understand !!
2022-06-07 00:12:34.950 6305-6325/com.mostafan3ma.android.pcm_helper10 E/AndroidRuntime: FATAL EXCEPTION: Instr: androidx.test.runner.AndroidJUnitRunner
Process: com.mostafan3ma.android.pcm_helper10, PID: 6305
java.lang.NoSuchMethodError: No virtual method shouldWaitForActivitiesToComplete()Z in class Landroidx/test/runner/AndroidJUnitRunner; or its super classes (declaration of 'androidx.test.runner.AndroidJUnitRunner' appears in /data/app/~~4CMeGrOsgkmvqLHECyOCZw==/com.mostafan3ma.android.pcm_helper10.test-N5A3R_1QMgwrtEkdIr0X8Q==/base.apk)
at androidx.test.runner.AndroidJUnitRunner.addListenersLegacyOrder(AndroidJUnitRunner.java:490)
at androidx.test.runner.AndroidJUnitRunner.addListeners(AndroidJUnitRunner.java:471)
at androidx.test.runner.AndroidJUnitRunner.onStart(AndroidJUnitRunner.java:443)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:2248)

REPLACE
testImplementation "org.hamcrest:hamcrest-all:$hamcrestVersion"
WITH
testImplementation 'org.hamcrest:hamcrest:2.2'
testImplementation 'org.hamcrest:hamcrest-library:2.2'

Related

error: [Hilt] Null element: java.lang.NullPointerException: Null element [Hilt]

I was writing unit tests for my room db operations, everything was working great but, I decided to write and inject the DataBaseBuilder within TestAppModule using Hilt, but seems like I am getting the following error when i run the tests. I also created a custom HiltRunnerClass and used it in gradle as testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"
here is full error
error: [Hilt]
Null element: java.lang.NullPointerException: Null element
at dagger.hilt.processor.internal.root.AutoValue_Root.<init>(AutoValue_Root.java:19)
at dagger.hilt.processor.internal.root.Root.createDefaultRoot(Root.java:46)
at
[Hilt] Processing did not complete. See error above for details.
1 error
here is the code
HiltTestRunner.kt
class HiltTestRunner:AndroidJUnitRunner() {
override fun newApplication(
cl: ClassLoader?,
className: String?,
context: Context?
): Application {
return super.newApplication(cl, HiltTestApplication::class.java.name, context)
}
}
NewsArticleDaoTest.kt
#RunWith(AndroidJUnit4::class)
#SmallTest
#HiltAndroidTest
class NewsArticleDaoTest{
#get:Rule
var hiltRule = HiltAndroidRule(this)
#get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
#Inject
#Named("test_db")
lateinit var database: NewsArticleDatabase
//private lateinit var database: NewsArticleDatabase
private lateinit var dao: NewsArticleDao
#Before
fun setup(){
hiltRule.inject()
dao = database.newsArticleDao()
// database = Room.inMemoryDatabaseBuilder(
// ApplicationProvider.getApplicationContext(),
// NewsArticleDatabase::class.java
// ).allowMainThreadQueries().build()
dao = database.newsArticleDao()
}
#After
fun teardown(){
database.close()
}
#Test
fun insertNewsArticle() = runTest {
val testArticle = NewsArticle("Time traveller shares footage from three weeks in the future showing who wins the World Cup","https://www.ladbible.com/sport/time-traveller-who-wins-world-cup-2022-20221128","https://images.ladbible.com/resize?type=webp&quality=70&width=671&fit=contain&gravity=null&dpr=2&url=https://eu-images.contentstack.com/v3/assets/bltcd74acc1d0a99f3a/bltb6064933a4b82b9c/6384c84adb8e364b186bfb6c/Most_prolific_speed_camera_in_the_UK_has_caught_almost_50_000_drivers_this_year_(42).png")
val testItem = listOf(testArticle)
dao.insertArticles(testItem)
val testFeed = NewsFeed(testArticle.url)
val feedTestItem = listOf(testFeed)
dao.insertNewsFeed(feedTestItem)
val allNewsArticles = dao.getAllNewsArticles().first()
assertThat(allNewsArticles).contains(testArticle)
}
#Test
fun deleteAllArticles()= runTest {
val testArticle = NewsArticle("Time traveller claims discovery of mysterious sea creature will change world","https://www.dailystar.co.uk/news/weird-news/time-traveller-claims-discovery-mysterious-28766022","https://i2-prod.dailystar.co.uk/incoming/article28766081.ece/ALTERNATES/s615b/1_A-SELF-proclaimed-time-traveller-from-2198-claims-experts-will-soon-make-a-chilling-ocean-discovery.jpg")
val testItem = listOf(testArticle)
dao.insertArticles(testItem)
val testFeed = NewsFeed(testArticle.url)
val feedTestItem = listOf(testFeed)
dao.insertNewsFeed(feedTestItem)
dao.deleteAllNewsFeed()
val allArticles = dao.getAllNewsArticles().first()
assertThat(allArticles).doesNotContain(testArticle)
}
}
TestAppModule.kt
#Module
#InstallIn(SingletonComponent::class)
object TestAppModule {
#Provides
#Named("test_db")
fun provideInMemoryDb(#ApplicationContext context: Context) =
Room.inMemoryDatabaseBuilder(context,NewsArticleDatabase::class.java )
.allowMainThreadQueries()
.build()
}
gladle(app)
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
id 'kotlin-parcelize'
id 'androidx.navigation.safeargs'
}
android {
compileSdkVersion 33
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.rimapps.wisetest"
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
//testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
testInstrumentationRunner "com.rimapps.wisetest.HiltTestRunner"
buildConfigField("String", "NEWS_API_ACCESS_KEY", news_api_access_key)
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
buildFeatures {
viewBinding true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs += "-Xopt-in=androidx.paging.ExperimentalPagingApi"
freeCompilerArgs += "-Xopt-in=kotlinx.coroutines.ExperimentalCoroutinesApi"
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.5.1'
//noinspection GradleDependency
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.5.3'
implementation 'androidx.navigation:navigation-ui-ktx:2.5.3'
testImplementation 'org.junit.jupiter:junit-jupiter'
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
// Glide
implementation "com.github.bumptech.glide:glide:4.14.2"
// Dagger Hilt
implementation "com.google.dagger:hilt-android:2.44.2"
kapt "com.google.dagger:hilt-android-compiler:2.44.2"
// Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4'
// Retrofit + GSON
implementation "com.squareup.retrofit2:retrofit:2.9.0"
implementation "com.squareup.retrofit2:converter-gson:2.9.0"
// Room
implementation "androidx.room:room-runtime:2.5.0-rc01"
kapt "androidx.room:room-compiler:2.5.0-rc01"
implementation "androidx.room:room-ktx:2.5.0-rc01"
// SwipeRefreshLayout
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
// Paging 3
implementation "androidx.paging:paging-runtime-ktx:3.2.0-alpha03"
// Fragment
implementation 'androidx.fragment:fragment-ktx:1.6.0-alpha04'
// Local Unit Tests
implementation "androidx.test:core:1.5.0"
testImplementation "junit:junit:4.13.2"
testImplementation "org.hamcrest:hamcrest-all:1.3"
testImplementation "androidx.arch.core:core-testing:2.1.0"
testImplementation "org.robolectric:robolectric:4.3.1"
testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
testImplementation "com.google.truth:truth:1.0.1"
testImplementation "org.mockito:mockito-core:3.4.6"
// Instrumented Unit Tests
androidTestImplementation "junit:junit:4.13.2"
androidTestImplementation "org.mockito:mockito-android:2.25.0"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4"
androidTestImplementation "androidx.arch.core:core-testing:2.1.0"
androidTestImplementation "com.google.truth:truth:1.0.1"
androidTestImplementation 'androidx.test.ext:junit:1.1.4'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'
androidTestImplementation "org.mockito:mockito-core:3.4.6"
androidTestImplementation 'com.google.dagger:hilt-android-testing:2.28-alpha'
kaptAndroidTest 'com.google.dagger:hilt-android-compiler:2.44.2'
debugImplementation "androidx.fragment:fragment-testing:1.5.5"
}
kapt {
correctErrorTypes true
}
gradle(project)
buildscript {
ext.kotlin_version = "1.7.20"
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.3.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.6.0-alpha04"
classpath "com.google.dagger:hilt-android-gradle-plugin:2.44.2"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

how to use aa_chart_view kotlin(getting runtime error)

I'm trying to plot some data using aa_chart_view library and I followed the instruction up until the point of binding activity_main.xml component to the code, the doc suggests using kotlin-android-extensions which is deprecated and the error suggests using kotlin-parcelize which I did and now I've got the following code:
package no.nordicsemi.android.uart.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartModel
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartType
import com.github.aachartmodel.aainfographics.aachartcreator.AAChartView
import com.github.aachartmodel.aainfographics.aachartcreator.AASeriesElement
import kotlinx.parcelize.Parcelize
import kotlinx.coroutines.launch
import no.nordicsemi.android.theme.view.SectionTitle
import no.nordicsemi.android.uart.R
import no.nordicsemi.android.uart.data.UARTRecord
import no.nordicsemi.android.uart.data.UARTRecordType
import no.nordicsemi.android.uart.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.util.*
private var _binding: ActivityMainBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
#Override
fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ActivityMainBinding.inflate(inflater, container, false)
val view = binding.root
return view
}
#Composable
internal fun OutputSection(records: List<UARTRecord>, onEvent: (UARTViewEvent) -> Unit) {
// val aaChartView = findViewById<AAChartView>(R.id.aa_chart_view)
val aaChartModel : AAChartModel = AAChartModel()
.chartType(AAChartType.Area)
.title("title")
.subtitle("subtitle")
.backgroundColor("#4b2b7f")
.dataLabelsEnabled(true)
.series(arrayOf(
AASeriesElement()
.name("Tokyo")
.data(arrayOf(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6)),
AASeriesElement()
.name("NewYork")
.data(arrayOf(0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5)),
AASeriesElement()
.name("London")
.data(arrayOf(0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0)),
AASeriesElement()
.name("Berlin")
.data(arrayOf(3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8))
)
)
binding.aaChartView.aa_drawChartWithChartModel(aaChartModel)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
}
Spacer(modifier = Modifier.size(16.dp))
val scrollState = rememberLazyListState()
val scrollDown = remember {
derivedStateOf { scrollState.isScrolledToTheEnd() }
}
LazyColumn(
modifier = Modifier.fillMaxWidth(),
state = scrollState
) {
if (records.isEmpty()) {
item { Text(text = stringResource(id = R.string.uart_output_placeholder)) }
} else {
records.forEach {
item {
when (it.type) {
UARTRecordType.INPUT -> MessageItemInput(record = it)
UARTRecordType.OUTPUT -> MessageItemOutput(record = it)
}
Spacer(modifier = Modifier.height(16.dp))
}
}
}
}
LaunchedEffect(records, scrollDown.value) {
if (!scrollDown.value || records.isEmpty()) {
return#LaunchedEffect
}
launch {
scrollState.scrollToItem(records.lastIndex)
}
}
}
}
fun LazyListState.isScrolledToTheEnd() = layoutInfo.visibleItemsInfo.lastOrNull()?.index == layoutInfo.totalItemsCount - 1
#Composable
private fun MessageItemInput(record: UARTRecord) {
Column(
modifier = Modifier.fillMaxWidth(),
horizontalAlignment = Alignment.End
) {
Text(
text = record.timeToString(),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurface
)
Spacer(modifier = Modifier.height(4.dp))
Column(
modifier = Modifier
.clip(RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp, bottomStart = 10.dp))
.background(MaterialTheme.colorScheme.secondary)
.padding(8.dp),
horizontalAlignment = Alignment.End
) {
Text(
text = "ksndfkjsndkjs",
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSecondary
)
}
}
}
#Composable
private fun MessageItemOutput(record: UARTRecord) {
// Column(
// modifier = Modifier.fillMaxWidth(),
// horizontalAlignment = Alignment.Start
// ) {
// Text(
// text = record.timeToString(),
// style = MaterialTheme.typography.labelSmall,
// color = MaterialTheme.colorScheme.onSurface,
// )
// Spacer(modifier = Modifier.height(4.dp))
// Column(
// modifier = Modifier
// .clip(RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp, bottomEnd = 10.dp))
// .background(MaterialTheme.colorScheme.primary)
// .padding(8.dp)
// ) {
// Text(
// text = record.text,
// style = MaterialTheme.typography.bodyMedium,
// color = MaterialTheme.colorScheme.onPrimary
// )
// }
// }
}
#Composable
private fun Menu(onEvent: (UARTViewEvent) -> Unit) {
Row {
IconButton(onClick = { onEvent(ClearOutputItems) }) {
Icon(
Icons.Default.Delete,
contentDescription = stringResource(id = R.string.uart_clear_items),
)
}
}
}
private val datFormatter = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH)
private fun UARTRecord.timeToString(): String {
return datFormatter.format(timestamp)
}
this is my app's build.gradle:
plugins {
id 'com.android.application'
id 'kotlin-parcelize'
id 'kotlin-android'
// id 'kotlin-android-extensions'
id 'kotlin-kapt'
id 'dagger.hilt.android.plugin'
}
apply from: rootProject.file("gradle/git-tag-version.gradle")
if (getGradle().getStartParameter().getTaskRequests().toString().contains("Release")){
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
}
android {
namespace 'no.nordicsemi.android.nrftoolbox'
compileSdk android_api_version
defaultConfig {
applicationId "no.nordicsemi.android.nrftoolbox"
minSdk android_min_api_version
targetSdk android_api_version
versionCode getVersionCodeFromTags()
versionName getVersionNameFromTags()
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables {
useSupportLibrary true
}
}
signingConfigs {
release {
storeFile file('../keystore')
storePassword System.env.KEYSTORE_PSWD
keyAlias System.env.KEYSTORE_ALIAS
keyPassword System.env.KEYSTORE_KEY_PSWD
}
}
buildFeatures {
viewBinding true
}
dataBinding {
enabled = true
}
buildTypes {
release {
minifyEnabled true
shrinkResources true
signingConfig signingConfigs.release
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 kotlin_version
}
hilt {
enableExperimentalClasspathAggregation = true
}
}
dependencies {
//Hilt requires to implement every module in the main app module
//https://github.com/google/dagger/issues/2123
implementation project(':profile_bps')
implementation project(':profile_csc')
implementation project(':profile_cgms')
implementation project(':profile_gls')
implementation project(':profile_hrs')
implementation project(':profile_hts')
implementation project(':profile_prx')
implementation project(':profile_rscs')
implementation project(':profile_uart')
implementation project(":lib_analytics")
implementation project(":lib_theme")
implementation project(":lib_utils")
implementation project(":lib_service")
implementation project(":lib_log")
implementation libs.nordic.theme
implementation libs.nordic.ble.common
implementation libs.nordic.ui.scanner
implementation libs.nordic.navigation
implementation libs.bundles.hilt
kapt libs.bundles.hiltkapt
implementation libs.bundles.icons
implementation libs.bundles.compose
implementation libs.androidx.core
implementation libs.material
implementation libs.lifecycle.activity
implementation libs.compose.lifecycle
implementation libs.compose.activity
testImplementation libs.test.junit
androidTestImplementation libs.android.test.junit
androidTestImplementation libs.android.test.espresso
androidTestImplementation libs.android.test.compose.ui
debugImplementation libs.android.test.compose.tooling
kapt "com.android.databinding:compiler:7.1.3"
}
kapt {
generateStubs = true
}
and the module's build.gradle:
apply from: rootProject.file("library.gradle")
apply plugin: 'kotlin-parcelize'
apply plugin: 'com.google.protobuf'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
//apply plugin: 'kotlin-android-extensions'
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.14.0'
}
// Generates the java Protobuf-lite code for the Protobufs in this project. See
// https://github.com/google/protobuf-gradle-plugin#customizing-protobuf-compilation
// for more information.
generateProtoTasks {
all().each { task ->
task.builtins {
java {
option 'lite'
}
}
}
}
}
dependencies {
implementation project(":lib_analytics")
implementation project(":lib_service")
implementation project(":lib_theme")
implementation project(":lib_utils")
implementation project(":lib_log")
implementation libs.room.runtime
implementation libs.room.ktx
kapt libs.room.compiler
implementation libs.nordic.ble.common
implementation libs.nordic.ble.ktx
implementation libs.nordic.theme
implementation libs.nordic.ui.scanner
implementation libs.nordic.navigation
implementation libs.bundles.datastore
implementation libs.bundles.compose
implementation libs.androidx.core
implementation libs.material
implementation libs.lifecycle.activity
implementation libs.lifecycle.service
implementation libs.compose.lifecycle
implementation libs.compose.activity
testImplementation libs.bundles.test
implementation('org.simpleframework:simple-xml:2.7.1') {
exclude group: 'stax', module: 'stax-api'
exclude group: 'xpp3', module: 'xpp3'
}
implementation 'com.github.AAChartModel:AAChartCore-Kotlin:-SNAPSHOT'
}
android {
buildFeatures {
viewBinding true
}
dataBinding {
enabled = true
}
namespace 'no.nordicsemi.android.uart'
}
and I uploaded the error into this pastebin(there is no specific error AFAIC)
Use dependency with version :
implementation 'com.github.AAChartModel:AAChartCore-Kotlin:7.1.0'

Creating a ViewModel causes the app to crash. (Kotlin/Android Studio)

I have been following a tutorial from Geeks for Geeks on how to make a simple note app for Android. I've practically copied to code word-by-word (except for a minor fix in the gradle file as advised from a Stack Overflow post and a comment in the YouTube comment section), yet the app crashes every time I open it even after clearing all the caches and rebuilding the project.
Links:
https://www.geeksforgeeks.org/how-to-build-a-simple-note-android-app-using-mvvm-and-room-database/
https://www.youtube.com/watch?v=D2F5t-phP04
Now, I know the problem with the code stems from the below command line.
viewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(application)
).get(NoteViewModel::class.java)
Every time I include the above line and launch the app, the app crashes, and my phone cannot open it. Commenting out the above line and the code below it allows the app to be opened without an issue.
(App gradle)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.notepractice"
minSdk 26
targetSdk 32
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 "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
implementation "androidx.activity:activity-ktx:$rootProject.activityVersion"
// Dependencies for working with Architecture components
// You'll probably have to update the version numbers in build.gradle (Project)
implementation 'androidx.fragment:fragment-ktx:1.1.0'
// Room components
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.2.0"
implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion"
// Kotlin components
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"
// UI
implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion"
implementation "com.google.android.material:material:$rootProject.materialVersion"
// Testing
testImplementation "junit:junit:$rootProject.junitVersion"
androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion"
androidTestImplementation ("androidx.test.espresso:espresso-core:$rootProject.espressoVersion", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation "androidx.test.ext:junit:$rootProject.androidxJunitVersion"
}
(Project gradle)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.31"
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle-api:7.2.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
plugins {
id 'com.android.application' version '7.2.0' apply false
id 'com.android.library' version '7.2.0' apply false
id 'org.jetbrains.kotlin.android' version '1.7.10' apply false
}
allprojects {
repositories {
google()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
/*
ext {
activityVersion = '1.4.0'
appCompatVersion = '1.4.0'
constraintLayoutVersion = '2.1.2'
coreTestingVersion = '2.1.0'
coroutines = '1.5.2'
lifecycleVersion = '2.4.0'
materialVersion = '1.4.0'
roomVersion = '2.3.0'
// testing
junitVersion = '4.13.2'
espressoVersion = '3.4.0'
androidxJunitVersion = '1.1.3'
}
*/
ext {
activityVersion = '1.2.3'
appCompatVersion = '1.3.0'
constraintLayoutVersion = '2.0.4'
coreTestingVersion = '2.1.0'
coroutines = '1.5.0'
lifecycleVersion = '2.3.1'
materialVersion = '1.3.0'
roomVersion = '2.3.0'
// testing
junitVersion = '4.13.2'
espressoVersion = '3.1.0'
androidxJunitVersion = '1.1.2'
}
(Main Activity)
package com.example.notepractice
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.util.*
class MainActivity : AppCompatActivity(), NoteClickInterface, NoteClickDeleteInterface {
lateinit var viewModel: NoteViewModel
lateinit var notesRV: RecyclerView
lateinit var addFAB: FloatingActionButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
notesRV = findViewById(R.id.RVNotes)
addFAB = findViewById(R.id.FABAddNote)
notesRV.layoutManager = LinearLayoutManager(this)
val noteRVAdapter = NoteRVAdapter(this, this, this)
notesRV.adapter = noteRVAdapter
viewModel = ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(application)
).get(NoteViewModel::class.java)
/*
viewModel.allNotes.observe(this, Observer { list ->
list?.let {
noteRVAdapter.updateList(it)
}
})
addFAB.setOnClickListener {
val intent = Intent(this#MainActivity, AddEditNoteActivity::class.java)
startActivity(intent)
this.finish()
}
*/
}
override fun onNoteClick(note: Note) {
val intent = Intent(this#MainActivity, AddEditNoteActivity::class.java)
intent.putExtra("noteType", "Edit")
intent.putExtra("noteTitle", note.noteTitle)
intent.putExtra("noteDescription", note.noteDescription)
intent.putExtra("noteId", note.id)
startActivity(intent)
}
override fun onDeleteIconClick(note: Note) {
viewModel.deleteNote(note)
Toast.makeText(this, "${note.noteTitle} Deleted", Toast.LENGTH_LONG).show()
}
}
(ViewModel)
package com.example.notepractice
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
class NoteViewModel(application: Application): AndroidViewModel(application) {
val allNotes: LiveData<List<Note>>
val repository: NoteRepository
init {
val dao = NoteDatabase.getDatabase(application).getNotesDao()
repository = NoteRepository(dao)
allNotes = repository.allNotes
}
fun deleteNote (note: Note) = viewModelScope.launch(Dispatchers.IO) {
repository.delete(note)
}
fun updateNote(note: Note) = viewModelScope.launch(Dispatchers.IO) {
repository.update(note)
}
fun addNote(note: Note) = viewModelScope.launch(Dispatchers.IO) {
repository.insert(note)
}
}
I'd like to end my question post with an actual question, but I am very inexperienced and cannot specify the problem. What would be the correct way to set up a ViewModel in Android with Kotlin?
Try initialising NoteViewModel like this inside your Activity.
private val viewModel: NoteViewModel by lazy {
ViewModelProvider(this).get(NoteViewModel::class.java)
}

Can't use suspend function in RoomDB Dao

What is going on with RoomDB and Kotlin coroutines? I am trying, again and again, to use suspend function in Room Dao but every time it shows an error. I even follow the android codelabs example. But it shows an error again. the app doesn't even build if I write suspend in Dao. But if I remove suspend keyword it builds successfully.
It shows the error below:
error: Type of the parameter must be a class annotated with #Entity or a collection/array of it.
kotlin.coroutines.Continuation<? super kotlin.Unit> continuation);
My Entity:
import androidx.room.Entity
import androidx.room.PrimaryKey
#Entity(tableName = "vocabulary")
class Vocabulary(
#PrimaryKey(autoGenerate = true)
val vocabularyId: Long,
val word: String,
val meaning: String,
val definition: String,
val example: String,
val partsOfSpeech: String,
val synonyms: String,
val antonyms: String,
val phonetics: String,
val folderId: Long,
val isLearned: Int
)
My Dao:
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
#Dao
interface VocabuilderDao {
#Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertVocab(vocabulary: Vocabulary)
}
My Database class:
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = [Vocabulary::class], version = 1, exportSchema = false)
public abstract class VocabuilderRoomDb : RoomDatabase(){
abstract fun vocabuilderDao(): VocabuilderDao
companion object{
#Volatile
private var INSTANCE: VocabuilderRoomDb? = null
fun getRoomDatabase(context: Context): VocabuilderRoomDb{
return INSTANCE ?: synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
VocabuilderRoomDb::class.java,
"vocabuilder_roomdb"
).build()
INSTANCE = instance
instance
}
}
}
}
My build.gradle (project level):
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.6.0'
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.2"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
ext {
activityVersion = '1.2.3'
appCompatVersion = '1.3.0'
constraintLayoutVersion = '2.0.4'
coreTestingVersion = '2.1.0'
coroutines = '1.5.0'
lifecycleVersion = '2.3.1'
materialVersion = '1.3.0'
roomVersion = '2.3.0'
// testing
junitVersion = '4.13.2'
espressoVersion = '3.1.0'
androidxJunitVersion = '1.1.2'
}
task clean(type: Delete) {
delete rootProject.buildDir
}
My build.gradle(module):
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.domesoft.vocabuilder"
minSdk 21
targetSdk 31
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'
}
}
dependencies {
implementation "androidx.appcompat:appcompat:$rootProject.appCompatVersion"
implementation "androidx.activity:activity-ktx:$rootProject.activityVersion"
// Dependencies for working with Architecture components
// You'll probably have to update the version numbers in build.gradle (Project)
// Room components
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$rootProject.lifecycleVersion"
implementation "androidx.lifecycle:lifecycle-common-java8:$rootProject.lifecycleVersion"
// Kotlin components
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$rootProject.coroutines"
api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$rootProject.coroutines"
// UI
implementation "androidx.constraintlayout:constraintlayout:$rootProject.constraintLayoutVersion"
implementation "com.google.android.material:material:$rootProject.materialVersion"
// Testing
testImplementation "junit:junit:$rootProject.junitVersion"
androidTestImplementation "androidx.arch.core:core-testing:$rootProject.coreTestingVersion"
androidTestImplementation ("androidx.test.espresso:espresso-core:$rootProject.espressoVersion", {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation "androidx.test.ext:junit:$rootProject.androidxJunitVersion"
}
If you using kotlin version (1.7.0) shoud work with room latest alpha version (2.5.0-alpha02)
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0"
implementation "androidx.room:room-runtime:2.5.0-alpha02"
implementation "androidx.room:room-ktx:2.5.0-alpha02"
kapt "androidx.room:room-compiler:2.5.0-alpha02"
If you want using room in stable version (2.4.2) should work with kotlin version (1.6.20)
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.20"
implementation "androidx.room:room-runtime:2.4.2"
implementation "androidx.room:room-ktx:2.4.2"
kapt "androidx.room:room-compiler:2.4.2"
I have tried both and they work. this is the reference: issue tracker
Update the Room version to 2.4.0-rc01.
In my case it solved the problem, and it works with Kotlin 1.6.0.
For me, kotlin-gradle-plugin 1.6.0 didn't work:
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0"
but 1.5.31 worked:
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.31'
Kotlin 1.6.0 with Room 2.4.0-rc01 worked too.
Thanks Stefano.

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'

Categories

Resources