I have no idea why i got this error when i invoke createBrowseRecord() function. My codes as follow, any ideas would be appreciated.
#Insert(onConflict = OnConflictStrategy.REPLACE)
fun createBrowseRecord(br:BrowseRecord)
#Entity(foreignKeys = [ForeignKey(entity = Composition::class,parentColumns =["id"],childColumns = ["compositionId"] ,onDelete = ForeignKey.CASCADE)])
data class BrowseRecord(#PrimaryKey val compositionId:String, val browseTime:Long)
#Entity
data class Composition(
val author: String,
val commentAmount: Int,
var cover: String,
val description: String,
val downloadURL: String,
val backGround:String,
val duration: String,
#PrimaryKey val id: String,
var isLike: Boolean,
val likeAmount: Int,
val title: String
)
Related
in my project , I have two Data Model class
first :
#Entity(tableName = TABLE_TASK)
data class TaskEntity(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "task_id") val taskId: Int,
#ColumnInfo(name = "task_title") val taskTitle: String?,
#ColumnInfo(name = "task_desc") val taskDesc: String?,
#ColumnInfo(name = "task_priority") val taskPriority: Int?,
#ColumnInfo(name = "task_status") val taskStatus: String?,
#ColumnInfo(name = "task_time") val taskTime: String?,
#ColumnInfo(name = "task_notify") val taskNotify: String?
)
and second :
data class SubtaskModel(
val subTasktitle : String?,
val subTaskStatus : Boolean?
)
and I wanted to add a filed in my first Data Model class as the code below (the last field ) :
#Entity(tableName = TABLE_TASK)
data class TaskEntity(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "task_id") val taskId: Int,
#ColumnInfo(name = "task_title") val taskTitle: String?,
#ColumnInfo(name = "task_desc") val taskDesc: String?,
#ColumnInfo(name = "task_priority") val taskPriority: Int?,
#ColumnInfo(name = "task_status") val taskStatus: String?,
#ColumnInfo(name = "task_time") val taskTime: String?,
#ColumnInfo(name = "task_notify") val taskNotify: String?,
#ColumnInfo(name = "task_subtask") val taskSubTask: MutableList<SubtaskModel>?
)
the error that i have got :
Cannot figure out how to save this field into database. You can
consider adding a type converter for it.
so I read(developer.android.com) and I did search about this but I couldn't figure out how can write Type Converter.
thank you
Follow below steps :
Step1. : create a convertor class -
class MyConverter {
#TypeConverter
fun listToJson(value: List< SubtaskModel >?): String = Gson().toJson(value)
#TypeConverter
fun jsonToList(value: String) = Gson().fromJson(value, Array<SubtaskModel>::class.java).toList()
}
Step 2 -> Add converter to your dataBase class
#Database(entities = [TaskEntity::class], version = 1)
#TypeConverters(MyConverter::class)
abstract class myDataBase : RoomDatabase() {
abstract fun myDao(): MyDao
}
That's it.
Here is my entity class:
#Entity
data class User(
#PrimaryKey
#Json(name = "id") val userId: String,
#Json(name = "login") val userName: String,
#Json(name = "avatar_url") val userAvatar: String,
val profile: Profile? = null
) : Serializable
Here is my Profile data class
data class Profile(
val avatar_url: String,
val bio: String,
val blog: String,
val company: Any,
val created_at: String,
val email: Any,
val events_url: String,
val followers: Int,
val followers_url: String,
val following: Int,
val following_url: String,
val gists_url: String,
val gravatar_id: String,
val hireable: Boolean,
val html_url: String,
val id: Int,
val location: String,
val login: String,
val name: String,
val node_id: String,
val organizations_url: String,
val public_gists: Int,
val public_repos: Int,
val received_events_url: String,
val repos_url: String,
val site_admin: Boolean,
val starred_url: String,
val subscriptions_url: String,
val twitter_username: Any,
val type: String,
val updated_at: String,
val url: String
) : Serializable
but every time I try to insert data into the table I am getting the error, how can I insert null data object in table while using room database?
The issue here is that Room doesn't know how to insert attribute of type Profile to the table.
The simple solution would be to use a type converter. Something like the following:
class DatabaseConverters {
#TypeConverter
fun toProfile(profileJson: String): Profile? {
return <Create a Profile object out of a JSON string>
}
#TypeConverter
fun fromProfile(profile: Profile?): String {
return <JSON string representation of Profile object>
}
}
In your case - you can use "" (empty string) when Profile is null.
More info about converters: Here
My Entity
#Entity(tableName = "my_entity_table")
internal data class MYEntity(
#PrimaryKey(autoGenerate = true)
val pcID: Int,
val server_id: String,
val name: String,
val detail: String,
val duration: Int,
val start_date : Long,
val end_date: Long,
val created_by_user_id: String,
val db_create_dttm: Long,
val db_update_dttm: Long,
val db_create_src: Long,
val db_update_src: Long
)
My dao query where I to select the duration,start_date and end_date
#Query("select duration,start_date,end_date from my_entity_table where id =:pcID")
suspend fun getDurationDetails(pcID:Int) : What should be the return type?
What should be the return type of the query ??
You could make a specific data class as model for your query with the specific fields:
data class ExampleModel(
#ColumnInfo(name = "duration") val duration: Int?,
#ColumnInfo(name = "start_date") val start_date: Long?
#ColumnInfo(name = "end_date") val end_date: Long?
)
And then use it as return:
#Query("select duration,start_date,end_date from my_entity_table where id =:pcID")
suspend fun getDurationDetails(pcID:Int) : ExampleModel
I don't think that using the Entity model is posible cause your Entity parameters are not nullable and you query just a few of that parameters.
I can't make the relation between these entities.
with SQL query I can make relation but with room not working.
I think this a room bug but don't know why. and taking me a lot of time.
using 2.2.6 version.
#Entity
data class Movie(
#SerializedName("country")
val country: String,
#SerializedName("genres")
val genres: List<String>,
#SerializedName("id")
#PrimaryKey(autoGenerate = false)
val id: Int,
#SerializedName("images")
val images: List<String>? = null,
#SerializedName("imdb_rating")
val imdbRating: String,
#SerializedName("poster")
val poster: String,
#SerializedName("title")
val title: String,
#SerializedName("year")
val year: String
)
#Entity
data class FavoriteMovie(
#PrimaryKey(autoGenerate = false)
val id: Int ,
val movieId: Int,
val createTime:String
)
data class MovieAndFavoriteMovie(
#Embedded val movie: Movie,
#Relation(parentColumn = "id", entityColumn = "movieId")
val favoriteMovie: FavoriteMovie
)
DAO
#Query("SELECT * FROM Movie")
#Transaction
fun getAllFavoriteMovies(): Flow<List<MovieAndFavoriteMovie>>
Error log
java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter favoriteMovie
at com.movie_explorer.data.database.MovieAndFavoriteMovie.<init>(Unknown Source:7)
at com.movie_explorer.data.database.dao.FavoriteMovieDao_Impl$5.call(FavoriteMovieDao_Impl.java:166)
at com.movie_explorer.data.database.dao.FavoriteMovieDao_Impl$5.call(FavoriteMovieDao_Impl.java:112)
at androidx.room.CoroutinesRoom$Companion$createFlow$1$1.invokeSuspend(CoroutinesRoom.kt:81)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
Issue Basics
ObjectBox version 2.5.1
Reproducibility: [always]
Hi, I am getting this error everytime I want to load my Object even though on saving I checked in the debugger and see that the relation target is not null and everything is saved correctly.
I am having those trhee entity classes
#Entity
data class NetflixCache (
val results: List<NetflixSearchResult>,
#Id var objectBoxId: Long?
) {
var searchParams: ToOne<SearchParams> = ToOne<SearchParams>(this, NetflixCache_.searchParams)
}
#Entity
data class SearchParams(val genrelist: String,
val type: String,
val imdbRatingMin: String,
val countryId: String,
val startYear: Int,
val endYear: Int,
val offset: Int? = 0,
val timeStamp: Long,
#Id var id: Long? = null)
#Entity
data class NetflixSearchResult (
val vtype: String?,
val img: String?,
val nfid: Long?,
val imdbid: String?,
val title: String?,
val clist: String?,
val poster: String?,
val imdbrating: Double?,
val synopsis: String?,
val titledate: Date?,
val year: Int?,
var id: Long,
#Id var objectBoxId: Long?
)
Using this code to save:
val cacheBox = LetsFlixApplication.boxStore.boxFor(NetflixCache::class.java)
val netflixCache = NetflixCache(searchResults, null)
netflixCache.searchParams.target = searchParams
cacheBox.put(netflixCache)
And this code to load:
val cachedResult = cacheBox.all //<-Exception is thrown here
As you can see in debugger when saving, ToOne Object is NOT null:
https://ibb.co/s3tdhqP
This is the exact exception message I am getting:
ToOne object is null inside com.haenles.letsflix.domain.NetflixCache
Issue for me was that data class was missing default values as recommended in the doc:
#Entity
data class User(
#Id var id: Long = 0,
var name: String? = null
)