https://kotlinlang.org logo
Docs
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
android
  • s

    Slackbot

    02/17/2020, 2:33 AM
    This message was deleted.
    :google: 1
    :stackoverflow: 1
    d
    d
    • 3
    • 2
  • o

    Ofir Bar

    02/17/2020, 9:46 AM
    for the first attempt (marked gray):
    Elvis operator always returns the left operand of non-nullable String
    for the 2nd attempt (marked yellow):
    condition currentUser?.office?.name.toString() is always 'true'
    Why is that not possible to be null?
    k
    • 2
    • 5
  • o

    Ofir Bar

    02/17/2020, 11:59 AM
    I mean, I want use a default placeholder if either the passed string “currentUser?.firstName” or “currentUser?.lastName” to
    getString()
    is null. Can I use this with elvis? I couldn’t find a way (unless using if/else,etc, just exploring something more clean)
    l
    • 2
    • 4
  • m

    Maurice Jouvet

    02/17/2020, 3:30 PM
    Hi, I would like to profile my application, but on Release variant. Is there a tool or a way to do it?
    d
    • 2
    • 1
  • d

    Doru N.

    02/17/2020, 5:05 PM
    Hi there! It seems like there is little to none information about the fact that android recreates the activity when an exception is thrown inside a ViewModel class (instead of just crashing the app). Upon doing so, some of my app resources are left in an inconsistent state. I would rather let it crash instead. Can anyone help me with some information in this regard?
    c
    w
    +2
    • 5
    • 12
  • g

    Geert

    02/18/2020, 8:22 AM
    My buiild.gradle is failing. I get the Error:
    Cause: only whitespace content allowed before start tag and not \u0 (position: START_DOCUMENT seen \u0... @1:1)
    while using `apply plugin: "androidx.navigation.safeargs"`` i
    a
    w
    • 3
    • 19
  • s

    Saket Poddar

    02/18/2020, 1:42 PM
    I am trying to control AnimatedVectorDrawable based on my network requests. I searched multiple articles but I can start the animation using Animate class, but cannot find to pin point how to handle animated vector drawables based on custom duration or trigger particular target, for example below loading class
    m
    d
    +2
    • 5
    • 5
  • v

    Vishvendu

    02/18/2020, 2:22 PM
    Hi is there any way we can hold the old position of the item in recycler view I want to show something if the new item click and if the same item click nothing should happen
    s
    • 2
    • 1
  • v

    Vishvendu

    02/18/2020, 2:26 PM
    So to save the item id --> holder.getItemId() ??
    p
    • 2
    • 25
  • o

    Ofir Bar

    02/18/2020, 7:07 PM
    Is it possible to create a generic function which limits the type
    T
    to 2 different objects? For example, here we limit to type
    Cat
    or
    Dog
    something like(this is pseudocode):
    private fun<T : Cat or Dog> convertToIntArray(objects: List<T>) : IntArray {
        val objectIds = arrayListOf<Int>()
        objects.forEach {
            objectIds.add(it.id)
        }
        return objectIds.toIntArray()
    }
    
    // Then pass something like this:
    val cats = convertToIntArray(oldListOfCats)
    val dogs = convertToIntArray(oldListOfDogs)
    k
    b
    • 3
    • 3
  • o

    Ofir Bar

    02/18/2020, 7:28 PM
    Is there a method that runs on a collection of objects, returning a collection that contains a specific field from the original collection? ( I tried searching through all collection methods with no success, no google help too) For example:
    data class Dog(val id: Int, val name: String)
    
    val dogs = arrayListOf(Dog(0, "jack"), Dog(1,"Jacky"), Dog(2, "Chan"))
    val listOfDogsId = dogs.somecoolmethodhere(it.id) // listOfDogsId = arrayListOf<Int>(0,1,2)
    b
    j
    t
    • 4
    • 5
  • v

    voben

    02/18/2020, 8:33 PM
    When using the new viewbinding, how can I create a ViewBinding for the root view similar to how databinding does it below?
    val viewDataBinding: T = DataBindingUtil.bind(itemView)
    j
    • 2
    • 1
  • i

    iex

    02/19/2020, 6:38 AM
    Can anyone please shed light into this? Seems Java interop issues
    class Foo<T> {
        fun <T> foo(a: T, b: T) = a == b // compiles
    }
    
    class MyCallback<T> : DiffUtil.ItemCallback<T>() {
        override fun areItemsTheSame(oldItem: T, newItem: T): Boolean =
            throw Error("TODO")
    
        override fun areContentsTheSame(oldItem: T, newItem: T): Boolean =
            oldItem == newItem // Doesn't compile - "equals in not implemented on T"
    }
    k
    m
    a
    • 4
    • 10
  • o

    Ofir Bar

    02/19/2020, 12:40 PM
    Hey guys, Is it possible to tell retrofit to ignore certain fields of an object when sending the object over the network? We have a request object
    Profession
    that we send to our backend using Retrofit.
    data class Profession (
    	@SerializedName("activeSince") var activeSince : Long?,
    	@SerializedName("name") var businessName : String?,
    	@SerializedName("description") var businessDescription : String?,
    	@SerializedName("licenseImageUrl") var licenseImageUrl : String?
    )
    Sometimes we send the entire object, but other times, I prefer to only send specific fields (for example, only the
    businessDescription
    and
    businessName
    ). Is it possible to tell retrofit to not include the other 2 fields in the network request? (
    activeSince
    and
    licenseImageUrl
    ). Note: I can’t send
    activeSince
    and
    licenseImageUrl
    as null. Our backend will send me back errors if I attempt to do that (edited)
    o
    d
    +3
    • 6
    • 10
  • o

    Ofir Bar

    02/19/2020, 4:28 PM
    Hey guys, I have a list
    returnedExpertiseFields
    inside a ViewModel. I want to initialize this list using a query to Room.
    returnedExpertiseFields
    gets returned before it is initialized with values from Room, as in the code below:
    fun getExpertiseFieldsById(expertiseFieldsIds: IntArray) : List<ExpertiseField>{
        var returnedExpertiseFields = listOf<ExpertiseField>()
    
        viewModelScope.launch {
            returnedExpertiseFields = mExpertiseFieldFieldsRepository.getExpertiseFieldsFromDatabaseById(expertiseFieldsIds)
        }
    
        return returnedExpertiseFields
    }
    returnedExpertiseFields
    will return an empty list of
    ExpertiseField
    . What can I do to make sure I always wait to Room query to be returned? I thought calling launch is synchronous? (If you need my repository code I will post it, I just thought it might not be necessary) Also, If any of you have any tips for debugging when using coroutines I will be glad to hear. I initially tought my Room query is broken. After long debugging I realized I am jumping between breakpoints rather them skipping them.
    o
    b
    • 3
    • 14
  • s

    Shreyas Patil

    02/19/2020, 5:51 PM
    Just published:aeroplane:new @kotlin library - #LiveStream-kt. It's a class which can observe💡 changes of data in real-time⚡and emit values too from any module in your app📱. Don't forget to give 🌟 on GitHub if you like it.😉 Link: https://github.com/PatilShreyas/LiveStream-kt
    w
    l
    +3
    • 6
    • 5
  • d

    Dr.jacky

    02/20/2020, 10:35 AM
    Hello everyone! Does
    @Parcelize
    works on Pair type as well? Or in the other hand, does it work on classes that implement
    Serializable
    . ? I tried on a sample app and it worked. But I have a crash in Crashlytics:
    Fatal Exception: java.lang.RuntimeException
    Parcelable encountered IOException writing serializable object (name = kotlin.Pair)
    keyboard_arrow_up
    🤔 1
    f
    b
    • 3
    • 8
  • b

    Brendan Weinstein

    02/20/2020, 6:14 PM
    Is there a common way that apps receiving an ACTION_SEND intent let the launching app know if the action was completed (eg user launches share sheet in App A -> taps whatsapp -> whatsapp populates message draft with link -> user taps send -> intent is returned with some special field denoting that a share send was completed)? edit: I've combed through the docs and can see how we can confirm that another app was launched from the share sheet; just haven't seen a way for us to confirm that that apps actually completed the intended action
    r
    • 2
    • 3
  • s

    shaktiman_droid

    02/21/2020, 2:49 AM
    I’ve a pretty weird question/requirement! I’m building an android SDK/library. In the library I want to know whether app is either • running on simulator • physical device • whether it’s in beta testing on google play • or it’s product build Based on my knowledge, I can only detect
    simulator
    vs
    physical
    based on some checks on
    Build
    class values But there is no way for SDK to know about
    beta testing
    vs
    production
    unless the developer of the app using the SDK provides that information via a
    public API
    Could someone confirm this ? OR if there is a way to do this then provide some insights.
    Reason is to route API calls and data to a particular endpoint so various data doesn’t end up skewing production data.
    I can do that via different API Keys for all for cases, but that’s off the limits right now.
    f
    r
    • 3
    • 6
  • b

    Bruno_

    02/21/2020, 2:41 PM
    I have a recycler view and I want to navigate to item details on click how do I do it? I mean this works just fine (from inside of adapter)
    holder.rootView.setOnClickListener {
                it.findNavController().navigate(R.id.numberDetailsScreen, bundleOf("numberName" to item.name))
            }
    the thing is that (from what I know) convention tells you to create Navigator interface but doing so would require passing the event up somehow so I could call this
    interface NumbersListNavigator {
        fun openNumberDetailsActivity(numberName: String)
    }
    l
    r
    • 3
    • 8
  • h

    Harun Artın

    02/21/2020, 8:50 PM
    Hello everyone. I am developing an online quiz application. Do you think Firebase is suitable for real-time multiplayer? The game I want to do will be like a quiz up application. Is there a platform you recommend if Firebase is not suitable? i didnt find any example. I'm a little nervous about latency. I couldn't decide between websocket or firebase. what is your suggestion?
    c
    • 2
    • 6
  • b

    Bruno_

    02/21/2020, 8:56 PM
    I'm doing an interview homework that's an android app, the only thing that's left to do is network error handling I have no idea how to approach this, could you help?
    b
    s
    +4
    • 7
    • 26
  • c

    Cody Engel

    02/22/2020, 2:34 PM
    Hey everyone, when using Kotlin Synthetics how do you name the view IDs? Do you stick with the traditional snake_case or do you go with camelCase? I’ve went with camelCase because it gives a consistent code style within the Kotlin files. Interested in what others do.
    🐍 4
    🐫 12
    s
    r
    +8
    • 11
    • 13
  • t

    tirgei

    02/23/2020, 7:30 AM
    Wrote an article on token based authentication using retrofit (& Kotlin): https://medium.com/@tirgei/token-authorization-with-retrofit-android-oauth-2-0-747995c79720
    👍 6
    d
    • 2
    • 2
  • o

    Ofir Bar

    02/23/2020, 11:31 AM
    Hi all, I made a code that returns a
    User
    object from the Shared Preferences. Here is the line of code I use:
    private val mCurrentUser = Defaults[PrefsKeys.user]!!
    So
    Defaults[PrefsKeys.user]!!
    returns the current
    User
    object stored in Shared Preference. The issue is when I change the value in the Shared Preference,
    mCurrentUser
    is still the same
    User
    object. Can I replace
    mCurrentUser
    to be an actual call to the SharedPreference? I guess I am trying to make something like an alias. Because calling Defaults[PrefKeys.user]!! everytime is not very readable.
    t
    • 2
    • 3
  • a

    Arslan Mushtaq

    02/23/2020, 7:21 PM
    I have a cart which stores data in Room Database. How is it possible for me to automatically update my Grand Total when an item Sub Total is changed within the Cart? I’m using the following SQLite functions:
    @Query("SELECT * FROM cart_table")
    fun getAllItemsFromCart(): LiveData<List<Cart>>
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(cart: Cart)
    
    @Query("DELETE FROM cart_table")
    suspend fun deleteAllItemsFromCart()
    
    @Delete
    suspend fun deleteItemFromCart(cart: Cart)
    
    @Query("SELECT COUNT(*) FROM cart_table")
    suspend fun itemCount(): Int
    
    @Query("SELECT SUM(total) FROM cart_table")
    fun getGrandTotal(): LiveData<Double>
    
    @Query("UPDATE cart_table SET quantity = quantity + 1 WHERE id = :id")
    suspend fun increaseQuantity(id: Int)
    
    @Query("UPDATE cart_table SET quantity = quantity - 1 WHERE id = :id")
    suspend fun decreaseQuantity(id: Int)
    a
    • 2
    • 6
  • s

    Slackbot

    02/24/2020, 6:36 AM
    This message was deleted.
    m
    t
    • 3
    • 2
  • o

    Ofir Bar

    02/24/2020, 9:08 AM
    Hi guys, I have 2 Activities, and 1 fragment inside one of them. `MainActivity`: Contains a Fragment
    UserFragment
    , the fragment display data of a User, the data is fetched from the SharedPreferences.
    EditUserActivity
    :Edits the data of the user, and once editing is done, this activity calls
    finish()
    and we go back to
    MainActivity
    , which displays
    UserFragment
    When returning to
    UserFragment
    , the data displayed is the old data for the user (the unedited data) I can think of 2 ways to make the fragment display fresh data, can anyone think of a smarter way, or explain which way below is better in terms of design? 1. Make
    UserFragment
    start
    EditUserActivity
    with
    startActivityForResult
    , and return a success or failure code, if success we do some data refresh. 2. Make
    UserFragment
    terminate itself once we navigate to
    EditUserActivity
    , and make
    EditUserActivity
    launch
    MainActivity
    with
    UserFragment
    on a backpress or successful save. Even if there is a way that is tricky and should not be in production i would like to know as I want to expand my skills please, thank you! 🙂
    3️⃣ 3
    f
    h
    +2
    • 5
    • 9
  • j

    jmfayard

    02/24/2020, 10:43 AM
    My Android emulator has no internet on a macOS that has internet. I have no idea how to investigate or what do do? Any idea? cause this is making me mad 🙂 Edit: after using Google DNS and wiping out the data and updating everything, the internet started to work again but I don't know why
    f
    a
    +4
    • 7
    • 19
  • o

    Ofir Bar

    02/24/2020, 1:22 PM
    Any idea why I can’t return a String to my
    uploadFileToFirebase
    function? What am I doing wrong? (part in red says):
    return is not allowed here
    r
    • 2
    • 7
Powered by Linen
Title
o

Ofir Bar

02/24/2020, 1:22 PM
Any idea why I can’t return a String to my
uploadFileToFirebase
function? What am I doing wrong? (part in red says):
return is not allowed here
r

ribesg

02/24/2020, 1:26 PM
You’re trying to return synchronously in an asynchronous code.
o

Ofir Bar

02/24/2020, 1:33 PM
@ribesg Can you please help? I am really short on time I need to upload a file to Firebase (uses Firebase callbacks), get that file download URL(uses Firebase callbacks), and sent it to my backend (uses coroutines) How can I combine the code above which uses Firebase callbacks with my backend coroutines call? (approximately, pseudocode is good too) This is my method that sends the file download URL to my backend:
r

ribesg

02/24/2020, 1:34 PM
Your function simply cannot return a String because it’s using callbacks, you could add a callback parameter of type
(String) -> Unit
to that function and call it instead of trying to return
(I actually would use
(Result<String>) -> Unit
and call it in the failure listener too)
You’re probably missing a failure listener on
downloadUrl
too
o

Ofir Bar

02/24/2020, 1:36 PM
true, i have added a failure listener thanks
View count: 6