https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
room
  • k

    Kiprop Victor

    12/07/2021, 4:41 PM
    Hey, I am trying to test Android room Dao function that returns a PagingSource. But following the docs, the test runs indefinitely. Check the following snippet:
    y
    j
    • 3
    • 10
  • m

    ms

    12/08/2021, 4:49 AM
    is there a way to perform an operation within the DAO after getting the result from Room, something like
    @Query("SELECT mutualFriends FROM friends where userId = :userId")
    fun getMutualFriends(userId: String): List<Friend> {
        // do some further operation with list
        // like filter or some other
    }
    k
    • 2
    • 4
  • t

    Tower Guidev2

    12/12/2021, 7:46 PM
    Hi, I am having diffulty understanding why I cannot retrieve the most upto date data from my room database when using paging3 library
    y
    • 2
    • 5
  • k

    Kestutis Povilaitis

    12/21/2021, 11:24 AM
    Hey I have a question about
    UUID
    usage in ROOM database with the new built in adapter. We decided to move from
    Long
    @PrimaryKey
    type to
    UUID
    because of integrity reasons. Now we need to migrate those ids. So when writing a migration we use raw SQL where we lose the ability to use built in converters (AFAIU at least) so we can’t insert it as
    String
    or something else (cant use the `UUIDUtil`from ROOM too). What would be the suggested way to migrate
    Long
    ids to
    UUID
    to use the build in adapter? Maybe someone else encountered a similar issue?
    • 1
    • 1
  • t

    Tower Guidev2

    01/04/2022, 10:11 AM
    Hi, im trying to use room with sqlite windowing functions LAG and LEAD
    y
    • 2
    • 6
  • v

    Vivek Sharma

    01/10/2022, 4:43 PM
    I have a question, when I have entity like this:
    @Entity
    data class Note(
        val title: String,
        val content: String,
        val timestamp: Long,
        val color: Int,
        @PrimaryKey val id: Int? = null
    )
    and when I create Note object, and passing 
    null
      to 
    id
     , what room will assign to it? In my case it is assigning 
    1, 2, 3, 4...
      like it is autoGenerating, is this correct what I am thinking? Though I am NOT having
    autoGenerate = true
    in
    @PrimaryKey
    y
    • 2
    • 2
  • a

    Aidan Low

    01/19/2022, 5:21 PM
    Is the conflict between
    @Transaction
    and
    -Xjvm-default=all
    a known issue? Building on android-room-with-a-view and adding
    -Xjvm-default=all
    to build.gradle and then adding a @Transaction’d
    deleteAllAndInsert
    to WordDao.kt results in
    WordDao_Impl.java:84: error: not an enclosing class: WordDao
            return WordDao.super.deleteAllAndInsert(word, __cont);
    p
    • 2
    • 5
  • m

    myanmarking

    01/25/2022, 4:29 PM
    Room has some persistent cache bug or sth. I have an entity with some values, was running on a device (had a migration and json file generated already). Then i decided to rename some variables (more specifically, they were plural, i took out the ‘s’). Then the project failed to compile, in the generated dao related to that entity. Was complaining about a method name was in plural and couldn’t find. Tried everything, cleared cache, deleted build files, deletes json schema. Nothing works but rename the table. It’s weird. It seems it has a broken disk cache somehow. idk
    • 1
    • 1
  • m

    Michael Marshall

    02/07/2022, 5:13 AM
    Does using
    @DatabaseView
    take up additional space in app memory (not storage)? Does it generate a temporary in-memory table of the view fields, or does it perform the
    SELECT
    query each time you access the view?
    e
    • 2
    • 2
  • u

    uli

    03/21/2022, 2:55 PM
    Hi there, is it possible to check a room encrypted database’s password? Calling
    databaseBuilder.openHelperFactory(SupportFactory(passPhrase)).build()
    with a wrong password does not fail as it seems to be ‘lazy’. (Well, it’s a factory). The failure only happens on first access. Additionally I have read somewhere, that accessing a Room/SQLite DB with a wrong password will corrupt it. Is that true?
    z
    • 2
    • 1
  • n

    natario1

    05/31/2022, 6:14 PM
    Is anyone aware of broken auto migrations? Looks like
    RenameColumn.Entries
    is not working properly if you specify more than 1 rename for the same table. Only one is picked
    k
    • 2
    • 2
  • k

    kotlinforandroid

    06/20/2022, 1:44 PM
    I store some JSON in my database. However, I changed the JSON representation. How can I migrate existing entries to the new format? I know how to generally do migrations. But I am not entirely sure how I can fetch the current entries, transform them and add them back to the database. Do I have to use raw SQL to fetch the entries or can I rely on older Room Daos during migration?
  • f

    fuad

    06/25/2022, 12:39 AM
    Room / Modules / architecture question... Typically with initializing Room you need a reference to Application Context. If you're building a library / SDK that needs to write to a Room database, what's the proper way to handle Room? Does the library own it's own Room instance? Do you want to create a singleton within your library to then reference Room from the library and to provide a handle to code using the library to read from the database? I found such suggestions in this SO post : https://stackoverflow.com/questions/62190220/room-database-setup-in-android-library-module but not really sure if this is actually the best or even a recommended approach.
    s
    • 2
    • 2
  • z

    zsperske

    06/30/2022, 8:12 PM
    I was trying to update to Kotlin
    1.7.0
    yesterday and Room started giving me issues
    error: Each bind variable in the query must have a matching method parameter. Cannot find method parameters for :expiringDate. - com.project.MyDao.getAll(java.util.Date)
    error: Unused parameter: arg0 - com.project.MyDao.getAll(java.util.Date)
    I tried disabling incremental room with no effect, only updating to the newest Room alpha fixed the issue (which isn’t an option for us, we don’t use alphas)
    h
    • 2
    • 2
  • t

    Tower Guidev2

    07/12/2022, 6:45 AM
    Hi does room support customisations to Dao generation that can resolve these build errors?
    Error:Not sure how to convert a Cursor to this method's return type
    m
    • 2
    • 3
  • h

    Hitesh Chopra

    07/31/2022, 5:40 PM
    Hi, I have been trying to test a database query which returns a PagingSource<>. Issue is how do I collect the value or list of data from the get query as the return type of query is pagingSource? I have tried the solution mentioned here -: https://stackoverflow.com/a/68320495/9607296 But the problem is this test keeps on running and never stops
    • 1
    • 1
  • i

    Isaac

    08/10/2022, 9:54 AM
    Does any one know why a ‘group by’ query in Room returns a Map<Key, List<Values>> as it’s supposed to, but List<Values> always has a size of 1?
  • j

    juliocbcotta

    09/01/2022, 9:12 AM
    Hey, is room KSP meant to be faster than with KAPT? I ran some benchmarks with gradle profiler using the latest version of room (2.5.0-alpha03) and the results are inconclusive for me...
    y
    • 2
    • 7
  • b

    Brandon Howard

    09/02/2022, 12:31 PM
    Hey, Is there any way to programmatically set the room db version number programmatically, at runtime? It seems like thats not possible based on the message im getting when i try
    An annotation argument must be a compile-time constant
    I’m just wondering if there’s another api that could help with this?
    m
    • 2
    • 4
  • m

    mattinger

    09/19/2022, 9:58 PM
    Anyone seen this error before? I’m getting this after upgrading my kotlin and gradle plugin:
    > java.lang.IllegalStateException: org.gradle.android.workarounds.RoomSchemaLocationWorkaround cannot be used with an explicit 'room.schemaLocation' annotation processor argument.  Please change this to configure the schema location directory via the 'room' project extension:
             room {
                 schemaLocationDir.set(file("roomSchemas"))
             }
    every bit of developer documentation i can find suggests that this it eh right right way to configure it:
    defaultConfig {
            javaCompileOptions {
                annotationProcessorOptions {
                    arguments += mapOf(
                        "room.schemaLocation" to "$projectDir/schemas",
                        "room.incremental" to "true",
                        "room.expandProjection" to "true"
                    )
                }
            }
        }
  • f

    FunkyMuse

    09/20/2022, 7:33 AM
    Hey guys, since KSP can be multiplatform, can Room with KSP be used to share multiplatform SQLite logic?
  • w

    Wishnuprathikantam

    09/27/2022, 4:45 AM
    [ksp] [MissingType]: Element 'com.project.db.converter.KotlinLocalDateTimeConverters' references a type that is not present. Any idea why this happens. seems to be working fine on version 2.4.3-alpha05 but having issue trying to update to 2.5.0-alpha03. The typeconverter is for kotlinx.datetime.LocalDateTime
  • r

    Ruben Quadros

    10/18/2022, 8:54 AM
    Hi everyone, how to get max value using room? More details in thread
    p
    • 2
    • 4
  • v

    v79

    10/18/2022, 7:30 PM
    I'll try to make this my only question - how do I update the primary key, or return the newly generated table row, after an insert? Code samples in thread... ``````
    p
    • 2
    • 17
  • v

    v79

    10/22/2022, 11:14 AM
    How do you fetch an initial value from the database when the viewmodel is first constructed? I'm happy to block the UI, I'm only trying to fetch a single Integer value. Because I can't do `val initialOdometerReading = vehicleRepository.getCurrentOdometer(_selectedVehicle)`because
    getCurrentOdometer
    is a suspend function (because, I think, all repository functions which call the DB are supposed to be suspend?) Note that I don't want a LiveData result - it's not going to change value suddenly!
    m
    • 2
    • 3
  • t

    Tower Guidev2

    10/27/2022, 9:00 AM
    Hi is it possible to have Room report when an Insert statement annotated with
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    actually replaces an existing row? or do i have to do something "clever" myself?
  • v

    v79

    10/29/2022, 8:38 AM
    How would I write a room query over a complex data type (like
    LocalDateTime
    ). I'm trying to write a query which would return all events in the last X number of days:
    fun getEventsWithin(days: Int): Flow<List<Event>>
    I'm really struggling to work out what the SQL would be. The
    Event
    entity has a column called
    dateTime
    of type
    LocalDateTime
    and I have written two
    @TypeConverter
    functions which convert between
    LocalDateTime
    and
    Long
    values.
    • 1
    • 2
  • i

    IsaacMart

    11/04/2022, 3:51 PM
    Any help with custom Type converters using koline serialization?
    • 1
    • 1
  • b

    Bwaim

    11/15/2022, 6:06 PM
    Hi, I was trying to return a multimap from a query to have a
    Map<CategoryEntity, List<CategoryEntity>>
    . So, making a query joining on the same table :
    @Query(
        "SELECT * FROM category as parent" +
        "JOIN category as child ON parent.id = child.parent_id"
    )
    fun loadCategoriesAndSubCategories(): Map<CategoryEntity, List<CategoryEntity>>
    It's not working because it's mapping with the column name. I tried to rename all the columns, but it doesn't work too. Someone knows if it's possible to do it ?
  • v

    v79

    11/19/2022, 9:39 AM
    Does it every make sense for me to need two Dao functions which return the same data, except one is
    LiveData
    and the other is not? Because I think I need that.
    m
    b
    r
    • 4
    • 5
Powered by Linen
Title
v

v79

11/19/2022, 9:39 AM
Does it every make sense for me to need two Dao functions which return the same data, except one is
LiveData
and the other is not? Because I think I need that.
Specifically, when I call the
init { ]
block in my ViewModel, I need to fetch a fixed value from the database. Currently, the database returns a LiveData object, as I need it like that elsewhere. So I think I'm going to end up in the state where my DAO and repo has the following almost-duplicate functions:
@Query("SELECT * FROM ChargeEvent WHERE id = :id")
    fun getChargeEventWithId(id: Long): LiveData<ChargeEvent?>

    @Query("SELECT * FROM ChargeEvent WHERE id = :id")
    fun getExistingChargeEventWithId(id: Long): ChargeEvent?
Which just looks like a code smell to me. Or rather, a lack-of-understanding smell.
m

Michael Marshall

11/21/2022, 3:08 AM
Can you just get the first element in the
LiveData
instead?
b

Brandon Howard

11/30/2022, 6:20 PM
I use two functions in my app for this situation - it works fine for me
r

rattleshirt

12/14/2022, 3:00 PM
You could also only have a function which returns a
Flow
and call
viewModelScope.launch { flow.firstOrNull() }
from
init
if you only need it once. Otherwise you could always extract the string from the query as const and reuse it in both
Both dao functions have their use cases. I see similar approaches with coroutines where you have 2 identical queries:
suspend fun
vs
Flow
View count: 18