https://kotlinlang.org logo
Title
n

Nizzle94

01/25/2018, 8:22 AM
Hello everyone. I have question about. Kotlin and room.
g

gildor

01/25/2018, 8:28 AM
I suppose you have NPE on
it.title!!
n

Nizzle94

01/25/2018, 8:29 AM
Yeah You are right. java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter author
How can I solve this one ?
g

gildor

01/25/2018, 8:29 AM
don’t use
!!
you can specify default value instead
title = it.title ?: "Some default value"
!!
is unsafe operation, you should always try to avoid use of
!!
.
!!
means “I sure this value is not null, so allow me to use it” so if value actually
null
your code will throw exception
Alternatively you can make
News.author
nullable, so in this case just assign null
n

Nizzle94

01/25/2018, 8:32 AM
Wooow thank you bro. You saved my day. I used this one “title = it.title ?: “Some default value”"
g

gildor

01/25/2018, 8:33 AM
You should read this part of official reference for better understanding: https://kotlinlang.org/docs/reference/null-safety.html
👍 1
Actually, according your error message you have null not on
title
but on
author
n

Nizzle94

01/25/2018, 8:35 AM
Yeah I changed all fields based on “title = it.title ?: “Some default value”"
By the way how can I auto increment primary key in room ?
@Entity(tableName = “news”) data class News constructor( @PrimaryKey(autoGenerate = true) var id: Int, var title: String, var author: String, var publishedAt: String ) { }
Yes, like this
autoGenerate should work
n

Nizzle94

01/25/2018, 8:38 AM
newsDao.insert( News( title = it.title ?: “”, author = it.author ?: “”, publishedAt = it.date ?:“” ) )
If i do like that there error I need to add id
g

gildor

01/25/2018, 8:38 AM
just make your id nullable
and assign null value there
var id: Int
->
var id: Int? = null
,
👍 1
also you should move this property from constructor to body of the class
n

Nizzle94

01/25/2018, 8:41 AM
@Entity(tableName = “news”) data class News constructor( var title: String, var author: String, var publishedAt: String ) { @PrimaryKey(autoGenerate = true) var id: Int? = null }
like that ?
g

gildor

01/25/2018, 8:41 AM
yes
n

Nizzle94

01/25/2018, 8:42 AM
Thank you
👌 1