Roomdb - Update #Embedded object within an Entity - android

I faced a problem when updating values of #Embedded object within an Entity.
Here is my Entity class:
#Entity
data class ReplyData(
#PrimaryKey val id: String,
#ColumnInfo(name = "sequence") val sequence: Int?,
#Embedded(prefix = "from") val from: From? <--- I want to update this #Embedded object within entity
)
#Entity
data class From(
#ColumnInfo(name = "id") val id: String? = "",
#ColumnInfo(name = "name") val name: String? = "",
#ColumnInfo(name = "avatar") val avatar: String? = "",
#ColumnInfo(name = "kind") val kind: String? = ""
)
I want to update these 3 values in 1 shot instead of updating them one-by-one with this query below.
#Query("UPDATE replydata.from SET name = :name, avatar = :avatar, kind = :kind WHERE id = :id")
fun updateReplyData(id: String, name: String, avatar: String, kind: String)
How can I achieve that without affecting the original entity (ReplyData)?
I tried this solution, but it is not working at all:
#Query("SELECT * FROM message WHERE id = :id")
suspend fun getReplyMessage(id: String): Message
#Update(entity = From::class)
suspend fun updateReply(msg: Message)
suspend fun updatePinMessage(id: String, from: From) {
val msg = getReplyMessage(id)
msg.from?.avatar = from.avatar
msg.from?.name = from.name
msg.from?.kind= from.kind
updateReply(msg)
}

Some notes:
#Embedded just shares own fields in the parent.
For instance the data table columns are:
[id | sequence | fromid | fromname | fromavatar | fromkind ]
NB: Better to use "from_" instead "from"
you can update these fields directly in your queries.

Maybe so late but ...
You need create support class
#Entity
data class ReplyData(
#PrimaryKey val id: String,
#ColumnInfo(name = "sequence") val sequence: Int?,
#Embedded(prefix = "from") val from: FromItem <- here
)
#Parcelize
data class FromItem(val item: From)
data class From(
val id: String? = "",
val name: String? = "",
val avatar: String? = "",
val kind: String? = ""
)
and update from
#Query("Update ReplyData set fromitem = :item where id = :id")
fun update(id: Long, item: From)
P.S:
I didn't check this code, maybe it has some errors

Related

Duh! Manually supply ID to Dao in Entity class

My entity:
#Entity(tableName = "accounts")
data class Account(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "user_id")
val id: Int,
#ColumnInfo(name = "first_name")
val firstName: String,
#ColumnInfo(name = "last_name")
val lastName: String?,
#ColumnInfo(name = "email")
val email: String
)
I am doing this:
fun register(email: String, name: String) {
return dbRepository.createAccount(Account(firstName = name, email = email))
}
Dao:
#Insert(onConflict = OnConflictStrategy.IGNORE)
fun insertAccount(account: Account) : Long
Problem: Requires me to add an ID via parameter to the Account object, annoying. Because I have annotated that user_id is #PrimaryKey(autoGenerate = true) and shouldn't be manually supplied.
You need to set id as var and give it 0 as default value:
#Entity(tableName = "accounts")
data class Account(
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "user_id")
var id: Int = 0,
#ColumnInfo(name = "first_name")
val firstName: String,
#ColumnInfo(name = "last_name")
val lastName: String?,
#ColumnInfo(name = "email")
val email: String
)
The default value is required to be able to create Account without providing the id because autoGenerate = true is not enough for the compiler to know that id is not required, and changing val to var because room in the background is going to parse that data and change that id so it must be mutable.
Note: This is room documentation for autoGenerate: if the field type is long or int (or its TypeConverter converts it to a long or int), Insert methods treat 0 as not-set while inserting the item.
If the field's type is Integer or Long (or its TypeConverter converts it to an Integer or a Long), Insert methods treat null as not-set while inserting the item.
So that's why the default value should be exactly 0 or null because room treats 0 and null as not-set and replace it with autoGenerated value.

How to use json array in Kotlin Using Moshi

[{"id":1,"first_name":"Lillis","last_name":"Hawgood"," cars":[ {"item":"Savana 1500"}, {"item":"Vibe"}, {"item":"Estate"} ]}]
data class MyData( val id: Int = 0, val first_name: String = "", val last_name: String = "", val cars: List
)
class Car { #Json(name = "item") var item: String? = null How to use Item in Data class the how ot print in main clas using moshi txtResult.text = "" for (myDataLst in myDataList ?: emptyList()) { txtResult.append("${myDataLst.first_name} - ${myDataLst.last_name} - ${myDataLst.cars} \n") }enter code here
I tried this way only first name and last showing but for cars showing some worng infor
Try this data classes i transform it using Json to Data Class plugin.
data class MyData(
val cars: List<Car>,
val first_name: String,
val id: Int,
val last_name: String
)
data class Car(
val item: String
)
class car : ArrayList<MyData>()
Firstly, please format your code, it's hard to read your code.
Secondly, you can use the Moshi like this:
#JsonClass(generateAdapter = true)
data class MyData(
#Json(name = "id") val id: String,
#Json(name = "first_name") val firstName: String,
#Json(name = "last_name") val lastName: String,
#Json(name = "cars") val cars: List<Car>
)
#JsonClass(generateAdapter = true)
data class Car(
#Json(name = "item") val item: String
)

Cant figure out return type of room db

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.

Room database relation not applying

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)

Adding a POJO into a Room database table

I have a POJO class OfflineDataRequestInfo which I want to insert into a database table as part of OfflineData which is my entity. but I get an error
How can I fix this please
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it. private final com.i6systems.offlineservicelibrary.offlineDatabase.OfflineDataRequestInfo requestInfoJsonX = null;
this is my code
data class OfflineDataRequestInfo (
val status: String,
val userId: String,
val fuelOrderId: String,
val timeStamp: String,
val fuelOrder: String
)
#Entity
data class OfflineData (
#PrimaryKey(autoGenerate = true) val uid: Int = 0,
#ColumnInfo(name = "request_info_json") val requestInfoJson: String?,
#ColumnInfo(name="request_code") val requestCode: String?,
#ColumnInfo(name="request_info_jsonX") val requestInfoJsonX: OfflineDataRequestInfo
)
This is not I insert
suspend fun insertOfflineData(requestInfoJson: String, requestCode: String, offlineDataRequestInfo: OfflineDataRequestInfo): Long {
var result: Long = 0
result = OfflineDatabaseManager.getInstance(app.applicationContext).insertOfflineData(
OfflineData(
0,
requestInfoJson,
requestCode,
offlineDataRequestInfo
))
return result
}
offlineHelper.insertOfflineData(
inPositionApiData.toString(),
"notifyInPosition",
OfflineDataRequestInfo(
"in-position",
action.userId,
id,
action.timestamp.toString(),
fuelOrderData.toString()
))
As i see you have 2 way to solve it :
Write a TypeConverter for your object OfflineDataRequestInfo
Add annotation #Embedded
#Embedded
#ColumnInfo(name="request_info_jsonX")
val requestInfoJsonX: OfflineDataRequestInfo

Categories

Resources