I'm new learning Kotlin and I'm developing a Notes app to practise with databases and viewModels.
I'm having trouble generating my database and the app crashes when it should generate the database and shows me this error on the logcat:
"java.lang.RuntimeException: cannot find implementation for com.example.blocnotas.database.AppDatabase. AppDatabase_Impl does not exist"
This is how I made my Database class:
package com.example.blocnotas.database
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = [Notes::class], version = 1, exportSchema = false)
abstract class AppDatabase: RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
#Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_notes_database")
.build()
INSTANCE = instance
return instance
}
}
}
My Application class:
package com.example.blocnotas
import android.app.Application
import com.example.blocnotas.database.AppDatabase
class NotesApplication : Application() {
val database: AppDatabase by lazy { AppDatabase.getDatabase(this) }
}
My app gradle:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
//id 'androidx.navigation.safeargs.kotlin'
}
android {
namespace 'com.example.blocnotas'
compileSdk 32
defaultConfig {
applicationId "com.example.blocnotas"
minSdk 19
targetSdk 32
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 {
viewBinding true
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.5.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.5.2'
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.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
}
Does anybody know how can i fix it and generate my database table?
I leave you the gitHub repository where i'm making it so if it can help get any extra necessary information: https://github.com/R3inbow/BlocNotasApp.git
I finally solved it changing in the gradle the "kapt" for "ksp" this way:
In dependencies:
ksp "androidx.room:room-compiler:$room_version"
In plugins:
id 'com.google.devtools.ksp' version '1.7.20-1.0.6'
Related
Yes I have already tried some old guides, I described it below.
I created new project for Room Database in Kotlin Android. I followed the official google documentation for it.
https://developer.android.com/training/data-storage/room
If I follow as per documentation I get error
java.lang.RuntimeException: cannot find implementation for com.example.laptopsdb.AppDatabase. AppDatabase_Impl does not exist
I also tried changing room-runtime to room-ktx but the error is same. Moreover, I tried adding id 'kotlin-kapt' and changing annotationProcessor to kapt but that give me following error, errors actually, bunch of them, while auto opening UserDao.java file
https://github.com/subjectOneThree/StackOverFLowShares/blob/main/Screenshot_20220715_215040.png
My code is almost stock according to documentation, however you can checkout if I made any stupid mistake
build.gradle (app)
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
//id 'kotlin-kapt'
}
android {
compileSdk 32
defaultConfig {
applicationId "com.example.laptopsdb"
minSdk 21
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
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
apply plugin: "kotlin-kapt"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def room_version = "2.4.2"
//implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
//kapt "androidx.room:room-compiler:$room_version"
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
User.kt
#Entity (tableName = "laptops")
data class User(
#PrimaryKey val uid: Int,
#ColumnInfo(name = "first_name") val firstName: String?,
#ColumnInfo(name = "last_name") val lastName: String?
)
UserDao.kt
#Dao
interface UserDao {
#Query("SELECT * FROM laptops")
suspend fun getAll(): List<User>
#Query("SELECT * FROM user WHERE uid IN (:userIds)")
suspend fun loadAllByIds(userIds: IntArray): List<User>
#Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
suspend fun findByName(first: String, last: String): User
#Insert
suspend fun insertAll(vararg users: User)
#Delete
suspend fun delete(user: User)
}
AppDatabase.kt
#Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "laptops"
).build()
val userDao = db.userDao()
GlobalScope.launch(Dispatchers.Default) {
userDao.insertAll(User(2,"Hello","World"))
val users: List<User> = userDao.getAll()
Log.d("Room Activity", users.toString())
}
}
}
Some of the older project, and a project from my friend have exactly the same code (as far as I have looked into it) and they are working fine. But now when I am trying to create new project it is giving me error. I have tried building several projects before posting here.
(comment) doing this:
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "laptops"
).build()
in the onCreate of mainActivity is a very bad way of creating a database instance, unless you want multiple database instances in one app!
solution:
try changing your build.gradle to this:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
apply plugin: 'kotlin-kapt'
android {
compileSdk 32
defaultConfig {
applicationId "com.example.laptopsdb"
minSdk 21
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
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
def room_version = "2.4.2"
kapt("androidx.room:room-compiler:2.4.2")
implementation("androidx.room:room-runtime:2.4.2")
implementation("androidx.room:room-ktx:2.4.2")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
EDIT:
After creating a project with the same code you have I noticed some rather strange bugs:
in your User.kt file you declared the table name of that entity to "laptops", but in your UserDao you still refered to a table named user, which does not exist (???), that's why room had some troubles with your dao
You declare your uid as Primary Key, which SHOULD NEVER be a duplicate, every single one of the keys should differ, yet in your main activity you use "userDao.insertAll(User(2,"Hello","World"))", which will result in a crash on second run, just remove that line
using "GlobalScope.launch(Dispatchers.Default)" to run a coroutine isn't really encouraged, GlobalScope is even marked in the android studio as a delicate API and using it without proper knowledge first may result in strange bugs or even memory leaks, just use a viewModel to handle all of the work
As I also stated before,
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "laptops"
).build()
do not use that to create database instance
update your build.gradle to:
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
apply plugin: 'kotlin-kapt'
android {
compileSdk 32
defaultConfig {
applicationId "com.example.laptopsdb"
minSdk 21
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
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// you may add the variable, just keep the version correct
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"
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
}
and the dao to:
#Dao
interface UserDao {
#Query("SELECT * FROM laptops")
suspend fun getAll(): List<User>
#Query("SELECT * FROM laptops WHERE uid IN (:userIds)")
suspend fun loadAllByIds(userIds: IntArray): List<User>
#Query("SELECT * FROM laptops WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
suspend fun findByName(first: String, last: String): User
#Insert
suspend fun insertAll(vararg users: User)
#Delete
suspend fun delete(user: User)
}
I am facing some issue using Room DB
java.lang.RuntimeException: cannot find implementation for
com.zeliot.roomtuto.db.NoteDB. NoteDB_Impl does not exist
below is my app grale
plugins {
id 'com.android.application'
id 'kotlin-android'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.zeliot.roomtuto"
minSdk 23
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
}
kotlinOptions {
jvmTarget = '1.8'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
//Room
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
// Coroutine Lifecycle Scopes
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.3.1"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
//coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
}
#Entity(
tableName = "note"
)
data class Note(
#PrimaryKey(autoGenerate = true)
var id:Int?=null,
val title :String,
val desciption:String,
val datetime:String,
)
#Dao
interface NoteDao {
#Insert
fun insert(note: Note)
#Delete
fun delete(note: Note)
#Query("select * from note")
fun getNotes(): LiveData<List<Note>>
#Update
fun update(note: Note)
}
#Database(
entities = [Note::class],
version = 1
)
abstract class NoteDB :RoomDatabase() {
abstract fun getNoteDao():NoteDao
companion object{
#Volatile
private var instance : NoteDB? = null
fun createDB(context: Context) :NoteDB{
return instance ?:
Room.databaseBuilder(
context.applicationContext,
NoteDB::class.java,
"Note_db.db"
)
.build()
}
}
}
UNABLE TO GET THE ANSWER ,I HAVE TRIED MANY SOLUTIONS BUT DIDN'T WORK.
I have tried many solution which are already available in stackoverflow but those solutions didnt work.
In Apple M1 chip we need to use room version of 2.4.0-alpha04.
plugins {
id 'com.android.application'
id 'kotlin-android'
id'kotlin-kapt'
}
implementation "androidx.room:room-runtime:2.4.0-alpha04"
implementation "androidx.room:room-ktx:2.4.0-alpha04"
kapt "androidx.room:room-compiler:2.4.0-alpha04"
issue tracker link https://issuetracker.google.com/issues/174695268?pli=1#comment13
Change :-
plugins {
id 'com.android.application'
id 'kotlin-android'
}
to
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
and then change
annotationProcessor "androidx.room:room-compiler:$room_version"
to
kapt "androidx.room:room-compiler:$room_version"
I am trying to call a suspend function using viewModelScope.launch in which "launch" is showing as Unresolved reference.
Here is build.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.mynotes"
minSdk 27
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
}
kotlinOptions {
jvmTarget = '1.8'
}
packagingOptions {
exclude 'META-INF/atomicfu.kotlin_module'
}
}
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"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
// 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"
}
and the ViewModel.kt
package com.example.mynotes
import android.app.Application
//import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.*
class NotesViewModel(application: Application) : ViewModel() {
private val repository : NotesRepository
val allNotes : LiveData<List<Notes>>
init {
val dao = NotesDatabase.getDatabase(application).getNotesDao()
repository = NotesRepository(dao)
allNotes = repository.allNotes
}
fun deleteNotes(notes: Notes) = viewModelScope.launch(Dispatchers.IO) {
repository.delete(notes)
}
}
In the function deleteNotes "viewModelScope.launch" is showing Unresolved reference: launch but there is no error while building the app but my app crash while running.
I think it's because of the way you are declaring the variable, since you are declaring it as a direct function, you can try the following:
fun deleteNotes(notes: Notes) {
viewModelScope.launch(Dispatchers.IO) {
repository.delete(notes)
}
}
It's possible the issue is related that when the method is declared and stored in memory, the scope hasnt been assigned yet.
Which version are you using?
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.1"
Try to use this case is different.
Try to invalide cache and restart if still not recognized
I'm trying to call the await() function in the
bookList = bookViewModel.getBookList().await()
in the Main Activity but it gives the error in the header.
Main Activity
#AndroidEntryPoint
class MainActivity : ComponentActivity() {
private val bookViewModel: BookViewModel by viewModels()
private var bookList : BookList? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GlobalScope.launch(Dispatchers.IO) {
bookList = bookViewModel.getBookList().await()
}
setContent {
LOTRAppTheme {
}
}
}
}
ViewModel
package com.example.lotrapp
import androidx.lifecycle.ViewModel
import com.example.lotrapp.models.BookList
import com.example.lotrapp.repository.BookRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
#HiltViewModel
class BookViewModel #Inject constructor(
private val repository: BookRepository
) : ViewModel() {
suspend fun getBookList() : BookList? {
return repository.getBookList()
}
}
Repository
package com.example.lotrapp.repository
import com.example.lotrapp.models.BookList
import com.example.lotrapp.network.RetrofitApi
import javax.inject.Inject
class BookRepository #Inject constructor(
private val retrofitApi: RetrofitApi
) {
suspend fun getBookList() : BookList?
{
return retrofitApi.getBookList().body()
}
}
Api
package com.example.lotrapp.network
import com.example.lotrapp.models.BookList
import retrofit2.Response
import retrofit2.http.GET
interface RetrofitApi {
#GET("book")
suspend fun getBookList() : Response<BookList>
}
Gradle:
plugins {
id 'com.android.application'
id 'kotlin-android'
id("dagger.hilt.android.plugin")
id("kotlin-kapt")
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.lotrapp"
minSdk 21
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'
useIR = true
}
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
kotlinCompilerVersion '1.5.10'
}
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
}
}
}
dependencies {
def compose_version = "1.0.2"
def lifecycle_version = "2.3.1"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation "androidx.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.compose.runtime:runtime-livedata:$compose_version"
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
// Lifecycles only (without ViewModel or LiveData)
implementation("androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version")
// Saved state module for ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version")
// Annotation processor
kapt("androidx.lifecycle:lifecycle-compiler:$lifecycle_version")
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation("androidx.lifecycle:lifecycle-common-java8:$lifecycle_version")
implementation 'androidx.activity:activity-compose:1.3.1'
testImplementation 'junit:junit:4.+'
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"
//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//Hilt
implementation("com.google.dagger:hilt-android:2.38.1")
kapt("com.google.dagger:hilt-android-compiler:2.38.1")
//Coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core-jvm:1.5.2")
}
kapt {
correctErrorTypes true
}
First I want to pull the list from the api and then show it in the UI with a Composable function (with LazyColumn) in setContent. It is enough to solve this error, but if you have better code suggestions, I would appreciate it. Thank you!
It doesn't really seem you need to invoke await() there. getBookList() returns BookList? directly, so just remove await() and it should be fine.
Additionally, you said you need to use this bookList in setContent. In that case you need to move setContent into launch block, below getBookList(). Right now setContent really executes before bookList is acquired. It is hard to provide more details without the full contents of setContent.
I have watched and read many tutorial on How to use Room persistence library with coroutines but whenever I use coroutine in my file it forces me to annotate my code with #InternalCoroutineApi but in the tutorial they don't need to annotate anything.
Now I'm wanted to know
1. What does this annotation means?
2. Why it is necessary?
3. How can I avoid this?
Even this answer doesn't help me either.
below is the how I created my data base and my build.gradle file
import android.content.Context
import androidx.room.Database
import androidx.room.Entity
import androidx.room.Room
import androidx.room.RoomDatabase
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.internal.synchronized
#Database(entities = [Post::class], version = 1, exportSchema = false)
public abstract class PostRoomDatabase: RoomDatabase() {
abstract fun getDao(): PostDao
companion object{
//Companion object provide the same functionality as the Static keyword in java
#Volatile
private var DATABASE_INSTANCE :PostRoomDatabase? = null
#InternalCoroutinesApi
fun getDatabase(context: Context) : PostRoomDatabase{
val tempInstance = DATABASE_INSTANCE
if(tempInstance != null){
return tempInstance
}
synchronized(this){
val instance = Room.databaseBuilder(
context.applicationContext,
PostRoomDatabase::class.java,
"post_database"
).build()
DATABASE_INSTANCE = instance;
return instance
}
}
}
}
Build.gradle file
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 28
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "vijay.bhadolia.seed"
minSdkVersion 23
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
// To inline the bytecode built with JVM target 1.8 into
// bytecode that is being built with JVM target 1.6. (e.g. navArgs)
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
dependencies {
def room_version = "2.2.5"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.2.2'
implementation 'androidx.navigation:navigation-ui-ktx:2.2.2'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//Circular images
implementation 'de.hdodenhof:circleimageview:3.1.0'
//Room database
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
def coroutines_version = "1.3.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version"
}
Your imports say:
import kotlinx.coroutines.internal.synchronized
Which is the internal API that it is complaining about. You should not be importing anything for the synchronized keyword, so simply remove that import line.