Hello everyone. I have question about. Kotlin and ...
# android
n
Hello everyone. I have question about. Kotlin and room.
g
I suppose you have NPE on
it.title!!
n
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
don’t use
!!
you can specify default value instead
Copy code
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
Wooow thank you bro. You saved my day. I used this one “title = it.title ?: “Some default value”"
g
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
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
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
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
@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
yes
n
Thank you
👌 1