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
android
  • i

    Ivann Ruiz

    09/24/2020, 8:05 PM
    Image
    1)
    r
    • 2
    • 3
  • n

    Nima

    09/25/2020, 3:35 AM
    Need help on the convincing the team not to use !! operator. Recently switched jobs and the code base is full of !!. Any article with a strong recommendation from Kotlin itself?
    👍 1
    g
    r
    +3
    • 6
    • 14
  • c

    Colton Idle

    09/25/2020, 4:13 AM
    Nothing wrong with !! IMO I think both @elizarov and @Adam Powell have both mentioned on here a few times that !! is a great way to assert an invariant. If they are using !! to simply satisfy the compiler, then yes that's bad. But if they are using it to say "this should never be null" then its fine to use and more convenient than other methods. Of course there are exceptions, but most people don't like !! because they think it looks ugly or screms that something is wrong. Which I found myself doing in the early days of kotlin, but now I use !! everywhere. 😄 tagged both of those users above because I don't actually want to misconstrue their opinions, but I think in general they both think !! is fine
    a
    g
    m
    • 4
    • 25
  • c

    coroutinedispatcher

    09/25/2020, 8:55 AM
    Hi guys. Just joined this slack channel. Passionate Android developer here. You may know me as the
    coroutineDispatcher
    by username, because I like scheduling stuff in my personal life and I use coroutines 😛 Usually I try to stay active in Stack Overflow, Reddit Androiddev, Kotlin channel. Also I love open source and try contributing if time. Proffesionally I have been working as an Android developer for 2 years and 11 months 🙈 and I love what I do. Currently based in Munich. See ya around 👋
    👋 9
    k
    b
    • 3
    • 6
  • k

    Klaus

    09/25/2020, 10:05 AM
    is there any way to determine the type of a visible item in RecyclerView by asking the adapter?
    :google: 1
    a
    j
    • 3
    • 5
  • g

    Galou Minisini

    09/25/2020, 2:31 PM
    Hi All! I have enable proguard in my project. The app is running great, no crashes and behave like it should. But I when I run the instrumentation tests suddenly I have a lot of weird error, mostly related to kotlin like:
    java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/collections/CollectionsKt;
    java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/ranges/RangesKt;
    And I find myself adding a bunch of rules to my proguard files to make my tests pass when my app is working fine. Any idea what I am doing wrong? Am I missing something?
    p
    • 2
    • 3
  • a

    Arief Hidayat

    09/25/2020, 3:05 PM
    Anyone know why my project xml become like this?
    :stackoverflow: 2
    o
    s
    • 3
    • 2
  • k

    Ken Maffei

    09/25/2020, 10:46 PM
    What's the best architecture for handling events in a recyclerview adapter that need to make network calls? So each cell can be clicked on to launch other actions, which may include network calls. I would assume you would not make network calls directly from the adapter. But should the adapter hold a reference to the fragment's ViewModel, and thereby be able to make network calls directly via the view model, or should the adapter just pass the call to the fragment and the fragment calls the viewModel? So it would be adapter -> ViewModel -> network call, or adapter -> fragment -> ViewModel -> network call. The adapter NOT holding a reference to the ViewModel feels right to me, but I'm wondering what's best, or if it matters.
    t
    • 2
    • 2
  • d

    David Ng

    09/26/2020, 2:43 AM
    Hi all, I'm trying to wrap my head around how coroutine/flow works. I have the following in my viewmodel
    private val _status = MutableLiveData<Status>()
    val status: LiveData<Status>
        get = _status
    
    fun getStatus(id: Int) {
        viewModelScope.launch {
            repository.getStatus(id)    // This return Flow<Status>
                .collect { _status = it}
        }
    }
    And I use data binding on my layout
    <TextView
        android:text="@{viewModel.status}" />
    The UI doesn't get updated to the latest value as the status come through from repository, the Main thread is being held up. If I switch the coroutine to use Dispatcher.IO, I got
    "java.lang.IllegalStateException: Cannot invoke setValue on a background thread"
    as the status need to be set on Main thread. I've tried using BroadcastChannel
    private val statusChannel = BroadcastChannel<Status>(Channel.CONFLATED)
    val status = statusChannel.asFlow().asLiveData()
    
    fun getStatus(id: Int) {
        viewModelScope.launch(<http://Dispatcher.IO|Dispatcher.IO>) {
            repository.getStatus(id)    // This return Flow<Status>
                .collect { statusChannel.offer(it) }
        }
    }
    But the idea of converting the channel back to flow feels odd. What's the best way to approach this?
    k
    i
    a
    • 4
    • 25
  • f

    Florian

    09/26/2020, 7:16 AM
    Do you use GlobalScope/NonCancelable for database operations in coroutines? If not, how do you avoid that the operation ends prematurely (for example by closing the app)
    t
    • 2
    • 3
  • f

    Florian

    09/26/2020, 9:52 AM
    Anyone here using Jetpack DataStore? When my fragment starts I want to load a value once. Right now I'm doing it like this, but it looks a bit awkward. Is this the correct approach? (this is inside
    onCreateOptionsMenu
    )
    m
    g
    • 3
    • 16
  • c

    coroutinedispatcher

    09/26/2020, 10:55 AM
    Is there any chance I can fix the indexing without upgrading/downgrading this version of canary? What I tried is only invalidate+restart and the indexing is still broken 😕 Can't even import a class or something, the whole package name comes when I type 🙈 Android studio version: 4.2 Canary 12 Gradle plugin: 4.2.0-alpha12
    b
    • 2
    • 1
  • m

    Mark

    09/27/2020, 4:57 AM
    Very often, after making a change to a
    ViewModel
    class, I get bizarre “error: cannot find symbol” compilation errors (in corresponding generated java class for ViewModel) where the only way forward is to do a clean build, and then everything compiles as expected. Is there some gradle setting I can tweak to avoid this?
    Execution failed for task ':mymodule:kaptDebugKotlin'.
    > A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
       > java.lang.reflect.InvocationTargetException (no error message)
    • 1
    • 1
  • n

    Nikhil

    09/27/2020, 9:55 AM
    Is jetpack and jetpackCompose a different thing?
    :google: 1
    c
    b
    +3
    • 6
    • 19
  • b

    bobby

    09/27/2020, 10:08 AM
    Hi everyone, I want to ask help from you guys to answer my question at Stack Overflow, it's about asymmetric encryption using RSA algorithm in Kotlin for Android env of course. I had searching the answer for days, but it's a dead end for me. Thank you all. Here's the link. https://stackoverflow.com/questions/64087039/incompatible-padding-mode-when-decyrpt-usiing-cipher-with-instance-rsa-ecb-pkcs
    c
    a
    • 3
    • 5
  • a

    Ayden

    09/27/2020, 12:45 PM
    Hi everyone. Does Raywenderlich course worth to subscribe?
    f
    • 2
    • 3
  • a

    Ayden

    09/27/2020, 1:24 PM
    I have ViewModelFactory which requires me to pass class as a constructor. But currently the class is an interface. May I know how can I achieve this?
    interface VoteRepository {
        fun getVoteDetails(): MutableLiveData<ArrayList<Vote>>
    }
    
    val voteViewModelFactory = VoteViewModelFactory(// I need to pass the VoteRepository here)
    :google: 3
    j
    s
    • 3
    • 9
  • s

    Sam

    09/28/2020, 4:24 AM
    Hello everyone, My app often takes a long time to review ( 2 weeks or 1 month), even though it has over 1 million users, in-app-purchase and is regularly updated new features/hotfix every 2 weeks. Does anyone have a way for Google to prioritize reviewing apps? 😥
    :stackoverflow: 3
    :google: 3
    d
    d
    • 3
    • 3
  • a

    Ayden

    09/28/2020, 3:57 PM
    Hi guys. I have the following code below, why my chart result always render before
    LiveData
    ?
    private fun getVoteData(): ArrayList<PieEntry> {
        ...
        val viewModel = ViewModelProvider(this, voteViewModelFactory).get(VoteViewModel::class.java)
        val liveData = viewModel.getVote()
        liveData.observe(viewLifecycleOwner, { vote ->
            vote.forEach {
                votes.add(PieEntry(it.total.toFloat(), it.name))
            }
        })
        return votes
    }
    
    private fun generateChart(binding: FragmentPieChartBinding, getVoteData: ArrayList<PieEntry>) {
        ...
    
        // Run before livedata execute
        Log.d("TEST", votes.toString())
    
        ...
        // Render chart result
    }
    :stackoverflow: 4
    c
    a
    +2
    • 5
    • 6
  • s

    Saul Wiggin

    09/28/2020, 6:32 PM
    Am trying to commit data to a room database
    AppExecutors.getInstance().diskIO().execute(new Runnable(){
    
        @Override
        public void run() {
            appDatabase.UIDao().insertUI(UI);
        }
    });
    but I’m getting an error`Attempt to invoke virtual method 'com.journaldev.firstandroidassignment.dao.UIDao com.journaldev.firstandroidassignment.database.AppDatabase.UIDao()' on a null object reference.` Any help would be much appreciated
    f
    s
    • 3
    • 3
  • c

    Chris Fillmore

    09/28/2020, 7:01 PM
    Hi folks, I’m curious if there is any point to using thread annotations with Kotlin, assuming you are not managing any threads directly, and just using coroutines? My use case is: I have a third-party library which throws an exception if certain methods are not run on the main thread. I would like to annotate these methods in a thin wrapper so that Android Studio will generate a warning. But I don’t see how to do this; when I annotate the methods and launch from e.g. Dispatchers.IO, I don’t get a warning
    g
    • 2
    • 1
  • v

    Vinod Rai

    09/29/2020, 7:01 AM
    -keepattributes *Annotation*, InnerClasses
    -dontnote kotlinx.serialization.SerializationKt
    -keep,includedescriptorclasses class com.yourcompany.yourpackage.**$$serializer { *; } # <-- change package name to your app's
    -keepclassmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
        *** Companion;
    }
    -keepclasseswithmembers class com.yourcompany.yourpackage.** { # <-- change package name to your app's
        kotlinx.serialization.KSerializer serializer(...);
    }
    The package name is changed,.. getting exception in kotlinx.serialization 1.0.0-RC
    Serializer for class 'e' is not found.
        Mark the class as @Serializable or provide the serializer explicitly.
    Data classes are in shared code. Why progaurd configuration is not working with minify enabled.  can anyone help what I am missing here? GitHub Kotlin/kotlinx.serialization Kotlin multiplatform / multi-format serialization - Kotlin/kotlinx.serialization
    d
    g
    • 3
    • 5
  • r

    ritesh

    09/30/2020, 10:54 AM
    Hi Everyone, Just wanted to understand regarding the MIT license. If there's a open source lib under MIT license and i copy one of it's whole class file in my android application. Do i need to give credits to the original author in the class file header, considering the legality of it. I read online and yes it makes sense to add credit as one of the reason and other reasons like helping future dev to go the source code as ref and all. But, just considering the legality of it, if someone's fails to add the credit - does that mean the MIT license is violated?
    s
    v
    • 3
    • 4
  • s

    Saul Wiggin

    09/30/2020, 10:57 AM
    Anyone has useful shortcuts for android studio? I’ve been adding Kotlin methods with command + enter on mac and found it very useful. Are there any other shortcuts I should know?
    m
    p
    • 3
    • 2
  • j

    Jason A. Donenfeld

    09/30/2020, 1:01 PM
    @Ian Lake @matvei @Ryan Mentley @tcracknell @jim @Adam Powell @Alexandre Elias [G] @msfjarvis Here's an interesting bug/race I've found in the kotlin coroutine port to Android/Jetpack. Let's assume we're operating inside of a fragment, using the fragment's lifecycle coroutine scope. Consider code like this:
    lifecycleScope.launch {
    	try {
    		// do stuff
    		delay(5000)
    		// do stuff
    	} catch (_: Throwable) {
    		requireContext()
    	}
    }
    When the Fragment is destroyed (by, e.g., the user pressing the back button), the Fragment's coroutine scope will be properly cancelled, as you'd expect. This in turn raises a CancellationException inside the scope. This exception is caught by our catch block, above. requireContext() is then called, and throws a new exception, because the context has already been destroyed. It seems like destruction of the context and such is happening in the wrong order. What should be happening instead is that context and binding and other various members that Fragment has should be set to null only after coroutines have exited. The example is contrived, but imagine something a bit more sophisticated, like:
    lifecycleScope.launch {
    	try {
    		binding!!.config = getConfigAsync()
    	} catch (_: Throwable) {
    		binding!!.config = null
    	}
    }
    Or, even more innocent looking:
    lifecycleScope.launch {
    	try {
    		// do something expensive
    	} catch (_: Throwable) {
    		Toast.make(ctx, getString(R.string.error_string), LONG).show()
    	}
    }
    That getString will crash too. You might respond that CancellationException should always be handled differently in every try-catch block ever for all coroutines. Maybe you're right. But that's a lot of refactoring and weirdness. And it seems like this would be better solved by just fixing the race of lifecycle shutdown vs context detachment. Does that seem reasonable?
    j
    c
    a
    • 4
    • 13
  • a

    Arief Hidayat

    10/01/2020, 6:46 AM
    #ask anyone know how to custom this callendar?
    :stackoverflow: 6
    :google: 3
    d
    • 2
    • 4
  • d

    David Ng

    10/01/2020, 10:47 AM
    Hi all, got a question on Kotlin/Coroutine, does viewModelScope cancel all child coroutine onCleared()? Here's my view model (use in Profile Fragment)
    class profileViewModel: ViewModel() {
        val profileRepository: ProfileRepository
        fun subscribeToProfile(id: Int) {
            viewModelScope.launch {
                profileRepository.subscribeToProfile(id)
            }
        }
    }
    My repository class
    class ProfileRepository {
        fun subscribeToProfile(id: Int) {
            withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
                .....       // Does this get cancelled onCleared()?
            }
        }
    }
    It seems to me the function in repository class still running despite I've navigated away from Profile Fragment. I've tried to debug on the view model and override the onCleared() function and call
    .cancel()
    override fun onCleared() {
        super.onCleared()
        viewModelScope.cancel()
    }
    I was able to breakpoint in
    onCleared()
    and execute the
    .cancel()
    but it doesn't cancel the job in repository. Am I missing any steps here?
    g
    • 2
    • 65
  • s

    Slackbot

    10/01/2020, 11:11 AM
    This message was deleted.
    g
    l
    • 3
    • 2
  • r

    Robby

    10/01/2020, 12:55 PM
    Hello, how to manage variable datatype var aa=0 and var aa=0.0 ? with out A*ny* key used?
    v
    f
    c
    • 4
    • 3
  • r

    Robby

    10/01/2020, 1:52 PM
    okay thank you But when i generate data Class then can we set any Double or Integer as Number?
    v
    • 2
    • 2
Powered by Linen
Title
r

Robby

10/01/2020, 1:52 PM
okay thank you But when i generate data Class then can we set any Double or Integer as Number?
v

Vampire

10/01/2020, 1:55 PM
Sure,
Number
is superclass of both,
Double
and
Int
(as well as
Long
,
Short
,
Float
and
Byte
). So if you have a
Number
typed variable, you can assign any number to it.
r

Robby

10/01/2020, 3:21 PM
oh, yes it is Help full me thank you @Vampire sir
View count: 1