Showing posts with label Room Database. Show all posts
Showing posts with label Room Database. Show all posts

Android Kotlin Room database, build error “A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution” on Android Studio Preview Apple M1

Component used: Room

Version used: 2.3.0

Devices/Android versions reproduced on: MacBook Pro M1 chip


Build failed on Apple M1 with Room database 2.3.0

Execution failed for task ':app:kaptDebugKotlin'.

> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction

   > java.lang.reflect.InvocationTargetException (no error message)

* Try:

Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Solution:

  implementation "androidx.room:room-runtime:2.3.0"

  annotationProcessor "androidx.room:room-compiler:2.3.0"

1. You can use Alpha Release version of room: 

implementation "androidx.room:room-runtime:2.4.0-alpha04"

annotationProcessor "androidx.room:room-compiler:2.4.0-alpha04"

Room Database Alpha Release version 2.4.0-alpha04 

2. Also updated project level build Gradle with latest Kotlin plugin version and latest Gradle plugin. (Need to update this because I was facing some error related to apply plugin: 'kotlin-android')

buildscript {
//    ext.kotlin_version = '1.3.61'
    ext.kotlin_version = '1.5.30'
    repositories {
        google()
        jcenter()
    }
    dependencies {
//        classpath 'com.android.tools.build:gradle:3.6.1'
        classpath 'com.android.tools.build:gradle:4.0.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

 

Check detailed log here:

> Task :app:kaptDebugKotlin

w: Runtime JAR files in the classpath should have the same version. These files were found in the classpath:

    /Users/pradiptilala/.gradle/caches/transforms-2/files-2.1/a6ee74fb178b3ea5a892efce09fbf14f/jetified-kotlin-stdlib-jdk7-1.3.61.jar (version 1.3)

    /Users/pradiptilala/.gradle/caches/transforms-2/files-2.1/120c1f3b8c4010532adc0c31034c2e5b/jetified-kotlin-stdlib-1.4.0.jar (version 1.4)

    /Users/pradiptilala/.gradle/caches/transforms-2/files-2.1/ce684c39ae6924170520b6f45161379f/jetified-kotlin-stdlib-common-1.4.0.jar (version 1.4)

w: Some runtime JAR files in the classpath have an incompatible version. Consider removing them from the classpath

> Task :app:kaptDebugKotlin FAILED

java.lang.IllegalStateException: failed to analyze: java.lang.reflect.InvocationTargetException

at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:56)

at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:182)

at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:165)

at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:55)

at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:84)

at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:42)

at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:104)

at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1558)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:566)

at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)

at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)

at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)

at java.base/java.security.AccessController.doPrivileged(Native Method)

at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)

at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)

at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)

at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)

at java.base/java.security.AccessController.doPrivileged(Native Method)

at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)

at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)

at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)

at java.base/java.lang.Thread.run(Thread.java:834)

Caused by: java.lang.reflect.InvocationTargetException

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.base/java.lang.reflect.Method.invoke(Method.java:566)

at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:76)

at org.jetbrains.kotlin.kapt3.base.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:35)

at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:224)

at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:187)

at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:98)

at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:97)

at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:107)

at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:82)

at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:557)

at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:82)

at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:107)

at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:548)

at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:177)

... 23 more

Caused by: com.sun.tools.javac.processing.AnnotationProcessingError: java.lang.ExceptionInInitializerError

at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:992)

at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:896)

at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1222)

at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1335)

at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1258)

at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1157)

... 40 more

Caused by: java.lang.ExceptionInInitializerError

at androidx.room.processor.DatabaseProcessor.doProcess(DatabaseProcessor.kt:82)

at androidx.room.processor.DatabaseProcessor.process(DatabaseProcessor.kt:57)

at androidx.room.RoomProcessor$DatabaseProcessingStep.process(RoomProcessor.kt:134)

at com.google.auto.common.BasicAnnotationProcessor.process(BasicAnnotationProcessor.java:330)

at com.google.auto.common.BasicAnnotationProcessor.process(BasicAnnotationProcessor.java:181)

at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt)

at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:147)

at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:980)

... 45 more

Caused by: java.lang.Exception: No native library is found for os.name=Mac and os.arch=aarch64. path=/org/sqlite/native/Mac/aarch64

at org.sqlite.SQLiteJDBCLoader.loadSQLiteNativeLibrary(SQLiteJDBCLoader.java:333)

at org.sqlite.SQLiteJDBCLoader.initialize(SQLiteJDBCLoader.java:64)

at androidx.room.verifier.DatabaseVerifier.<clinit>(DatabaseVerifier.kt:68)

... 53 more

Execution failed for task ':app:kaptDebugKotlin'.

> Internal compiler error. See log for more details


android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed:

Reason for Exception is that Gson treats “missing” values as “null”
Caused by: android.database.sqlite.SQLiteConstraintException:
NOT NULL
constraint failed: (code 1299 SQLITE_CONSTRAINT_NOTNULL)
You might come across this error when you are using Room database on Android. This happens because the generated schema for your tables mark some of the table’s columns as NOT NULL.

For example, if you Entity class looks like this:

Model Class Book:
package com.geekscompete.gate_isro_cs.ugc_net_preparation.database.models

import androidx.room.Entity
import androidx.room.PrimaryKey
import com.geekscompete.gate_isro_cs.ugc_net_preparation.database.BaseOb

@Entity(tableName = "book")
class Book(
        @PrimaryKey(autoGenerate = true)
        var objectId: Int = 0,

        id: String ="",
        data: String = "",
        title: String ="",
        description: String ="",
        last_updated: String ="",
        logo_url: String ="",
        orderno: Int = 0,
        tags: String="",
        type: Int = -1,
        btm_color: String="#F0513C",

       var price: Int,
        var redirect_url: String,
        var tag: String
): BaseOb(id,data,title,description,last_updated,logo_url,orderno,tags,type,btm_color)

Data I am getting from API is as below:
{
id: 1,
title: "NTA UGC NET/SET/JRF - Paper 1",
description: "This book, in its third edition, is designed and developed for students who aspire to build a career in academics and research field",
image_url: "https://images-na.ssl-images-amazon.com/images/I/71%2BZPvi7ZlL.jpg",
store_logo_url: "https://images-na.ssl-images-amazon.com/images/G/01/rainier/available_at_amazon_1200x600_Nvz5h2M.png",
price: 411,
redirect_url: "https://www.amazon.in/NTA-UGC-NET-SET-JRF/dp/9353433746/ref=as_li_ss_il?crid=2EYYT7DF8WXMX&keywords=ugc+net+paper+1+2019&qid=1564293960&s=gateway&sprefix=ugc+net+,aps,281&sr=8-1-spons&psc=1&linkCode=li2&linkId=8424f35e3b5163df827e84af24007fb9&language=en_IN",
tag: "UGC NET PAPER 1"
}

There was no data field in the API response and I am parsing using Gson.
The generated columns like title, description, data and logo_url will be marked as NOT NULL. And thus, when you try to add a record with one of these values as null, you will get an SQLiteConstraintException.
val title: String
In Kotlin, this means that title can never be null.

To fix this, you just need to change the Entity class a bit, and allow the fields to be Nullable.
@Entity(tableName = "books")
data class Book(
    @PrimaryKey
    val id: Int,
    val title: String?,
    val description: String?,
    val info: String?,
    val type: Int,
    val url: String?
)

08-31 18:19:06.031 8364-8450/com.geekscompete.gate_isro_cs.ugc_net_preparation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #2
    Process: com.geekscompete.gate_isro_cs.ugc_net_preparation, PID: 8364
    android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: book.data (code 1299)
        at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
        at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:780)
        at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
        at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
        at androidx.sqlite.db.framework.FrameworkSQLiteStatement.executeInsert(FrameworkSQLiteStatement.java:51)
        at androidx.room.EntityInsertionAdapter.insert(EntityInsertionAdapter.java:97)
        at com.geekscompete.gate_isro_cs.ugc_net_preparation.database.models.BookNewDao_Impl.insertAll(BookNewDao_Impl.java:267)
        at com.geekscompete.gate_isro_cs.ugc_net_preparation.quiz_attempts.QuizListFragment_new$getBooks$1$1.run(QuizListFragment_new.kt:410)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
        at java.lang.Thread.run(Thread.java:818)

References best:
https://techdroid.kbeanie.com/2018/11/24/room-database-kotlin-nullable-column/
https://www.bignerdranch.com/blog/when-nullability-lies-a-cautionary-tale/

android room unique constraint (Kotlin)

Kotlin code:


Single column unique (e.g. id_key only).

@Entity(tableName = "user",indices = [(Index(value = ["id_key"], unique = true))])
data class User (

  @PrimaryKey(autoGenerate = true)
    var id: Int = 0
 
  @ColumnInfo(name = "id_key")
    var id_key: String = ""

    @ColumnInfo(name = "first_name")
    var first_name: String = ""

@ColumnInfo(name = "last_name")
    var last_name: String = ""
}


How to add unique constraint in room database to multiple column

Combine two columns to be unique (e.g. first_name and last_name).

@Entity(tableName = "user",indices = arrayOf(Index(value = ["first_name", "last_name"], unique = true)))
data class User (
.....
}


Multiple unique constaints.

@Entity(tableName = "user", indices = [Index(value = ["id_key"]),Index(value = ["first_name", "last_name"],unique = true)])
....
}

Popular Posts