I cannot find anything about this type of relation (everything is about one-to-one, one-to-many or many-to-many). And even those look a little bit too complicated for what I need.
I have a table with tasks and a table with images. Multiple tasks can have the same image in order to save space (the image is not deleted when the task is deleted). I have an entity for the task
import android.graphics.Bitmap
import androidx.room.*
#Entity(tableName = "tasks")
class Task(
#PrimaryKey(autoGenerate = true)
val id: Long,
val imageId: Long = 0,
// this needs a foreign key to Image
val image: Image
)
and another one for the image
import androidx.room.ColumnInfo
import androidx.room.PrimaryKey
#Entity(tableName = "images")
class Image (
#PrimaryKey(autoGenerate = true)
val id: Long,
val title: String,
#ColumnInfo(typeAffinity = ColumnInfo.BLOB)
val data: ByteArray? = null
)
How do I add a foreignKey for the imageId column so that it points to an Image? Can I directly obtain an Image object as a member of Task without having to create another class?
You have to use one-to-many relationship here. There is an example from d.android.com. If you will do like that you will have a Task entity, an Image entity and data class TaskWithImage, just like in the example provided.
data class TaskWithImage(
#Embedded val task: Task,
#Embedded(prefix = "img_") val image: Image
)
#Query("""
SELECT * FROM tasks
INNER JOIN images as img_ ON tasks.id = img_.id
""")
fun getTasksWithImage(): List<TaskWithImage>
Related
I have scenario where in I have a "Lookup Table" class that holds getters and setters for multiple class types. As I'm interfacing with a database, I need to provide a way to provide a result boolean and then the class instance which was requested.
For example. Say I have an AssetStatus, StockItemStatus and NominalCode class. I would have to write the following data class for each:
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: AssetStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: StockItemStatus? = null,
)
// or
data class LookupResult(
val wasSuccessful: Boolean = false,
val resultClass: NominalCode? = null,
)
Ideally I don't want to have to repeat myself so I was wondering if I could write one data class (or normal class?) which is able to return one of my multiple Lookup classes?
Initially I thought it would have needed to be Any but after looking into this, that might not be the best case for what I want.
So is there a way of sticking to writing once but not repeating? Or is it something I have to do?
Edit:-
All of my class types would have the following structure (note: I'm using Spring Boot as back end) :
#Entity
#Table(name = "lookup_asset_status")
data class AssetStatus(
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "asset_status_id")
val id: Long? = null,
#Column(name = "asset_status_name")
val name: String = "",
)
...
// Repeat for each entity type
...
If I understand correctly, you want something like this:
data class LookupResult<T>(
val wasSuccessful: Boolean = false,
val resultClass: T? = null,
)
Each of the classes would be written as LookupResult<AssetStatus>, LookupResult<StockItemStatus> and LookupResult<NominalCode>.
If your method needs to be able to return any of those three classes, then it should be declared to return LookupResult<*>. Note that you can only access the members of Any when you access the resultClass of a LookupResult<*>, because you don't know which exact look up result it is.
in my application ,apart from the primarykey of a user ,I will still need to generate a unique ID(12 -15 charactors) for showing to the public .
I am new with Room ,Could you please take a look my code ?
Thank you so much in advance !
#Entity
data class UserInfo(
#PrimaryKey(autoGenerate = true)
val userId:Int = 0,
val image: String,
val imageSource : String,//Local or Online
val username : String,
val gender :String,
val userPublicId:String, //this is the id that need to generate 12-15
val birthday : String,
val userIntro :String,
)
As mentioned #Tenfour04 you can use some ways to generate random string. I think org.apache.commons.lang3.RandomStringUtils is a good choice. For exmaple look at the following methods: randomAscii, randomAlphabetic, randomAlphanumeric.
Basically I have a data class like
data class House(
val bedroom: Bedroom,
val livingroom: Livingroom
)
data class Bedroom(
val bed: String,
val pillows: List<String>
)
data class Livingroom(
val sofa: String,
val tv: String
)
I wonder how to map the House data model to a map with only one level:
{
bed = "some-bed",
pillows = ["pillow-a", "pillow-b", "pillow-c"],
sofa = "some-sofa",
tv = "some-tv"
}
I tried gson by first transforming it to a json then to map, but it will give me nested maps
I have following models
#RealmClass
open class Sport (#PrimaryKey open var sportId: Long = 0,
//...
open var events: RealmList<Event> = RealmList(),
) : RealmObject()
#RealmClass
open class Event(
#PrimaryKey var id: Long = 0L,
//...
open var defaultGame: Game? = null
) : RealmObject()
and following query
fun getSports(): RealmResults<Sport> = realm.where(Sport::class.java)
.isNotNull("events.defaultGame")
.distinct("sportId")
.sort(orderSportFields, orderSport)
.findAll()
When I call getSports() function, I receive:
java.lang.IllegalArgumentException: Illegal Argument: isNotNull() by nested query for link field is not supported.
How to change my query to get the list of sports where each sport has at least one event with defaultGame field being not null?
Thanks!
I parsed a json string to the following object structure using gson:
data class Base (
val expand: String,
val startAt: Long,
val maxResults: Long,
val total: Long,
val issues: List<Issue>
)
data class Issue (
val expand: String,
val id: String,
val self: String,
val key: String,
val fields: Fields
)
data class Fields (
val summary: String,
val issuetype: Issuetype,
val customfield10006: Long? = null,
val created: String,
val customfield11201: String? = null,
val status: Status,
val customfield10002: Customfield10002? = null,
val customfield10003: String? = null
)
Everything works fine and also the object model is correct, because I can access each element of the object.
However, I encountered the problem that I dont know how to get a list of all field-elements. Right now, I have only figured out how to access one item (by using an index and get()-function):
val baseObject = gson.fromJson(response, Base::class.java)
val fieldsList = baseObject.issues.get(0).fields
I actually want to have a list of all field elements and not just one. Is there a gson function allowing me to do that? I couldn't find anything about it in the gson documentation for java.
You don't have to look for some gson function when you've already created a baseObject. You just need to get from each issue it's fields and you can use a map function to achieve this, it will convert each issue to a new type so you can get issue fields there
val fieldFromAllIssues: List<Fields> = baseObject.issues.map { it.fields }
it in this context is a one issue. More explanation about it is here