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
  • r

    ritesh

    03/27/2020, 12:28 PM
    Anyone faced this issue with epoxy. SetData on epoxy controller isn't appending to the old list but overwriting it.
    class KnowledgeArticleListController : Typed2EpoxyController<List<Article>, KnowledgeArticleListActionHandler>() {
      override fun setDebugLoggingEnabled(enabled: Boolean) {
        super.setDebugLoggingEnabled(true)
      }
      override fun buildModels(data: List<Article>, listener: KnowledgeArticleListActionHandler) {
        data.forEachIndexed { index, article ->
          knowledgeArticleListItemView {
            id(article.id)
            article(article)
            listener(listener)
            lastItem(index == data.lastIndex)
          }
        }
      }
    }
    @EpoxyModelClass(layout = R.layout.knowledge_article_list_item)
    abstract class KnowledgeArticleListItemView : EpoxyModelWithHolder<ViewViewHolder>() {
    
      @EpoxyAttribute
      var category: Category? = null
    
      @EpoxyAttribute
      var article: Article? = null
    
      @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
      lateinit var listener: KnowledgeArticleListActionHandler
    
      @EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
      var lastItem: Boolean = false
    
      override fun bind(holder: ViewViewHolder) {
        if (category != null) {
        
        } else if (article != null) {
          
        }
    
        holder.knowledgeArticleListItemCell.showTopBorder = false
    
        // don't show bottom border if last item, toolbar border is there
        holder.knowledgeArticleListItemCell.showBottomBorder = !lastItem
      }
    
      override fun unbind(holder: ViewViewHolder) {
        holder.knowledgeArticleListItemCell.setOnClickListener(null)
      }
    }
    
    class ViewViewHolder : KotlinEpoxyHolder() {
      val knowledgeArticleListItemCell by bind<StandardCell>(R.id.knowledgeArticleListItemCell)
    }
    d
    n
    a
    • 4
    • 12
  • s

    Smith

    03/27/2020, 7:59 PM
    I’m trying to set insets to my cardView(“titleBar”) but it isnt reflected in the app. But when i debug it i can see statusBarHeight is changed and should be updated in layoutParams
    • 1
    • 1
  • t

    Travis Griggs

    03/27/2020, 10:23 PM
    I don’t know if this is Android specific or generally applicable. I just lost a day (at least) worth of work due to this little surprise:
    val family = 42
    val friends = 0
    println("Family:Friend ratio = ${family / friends}")
    What my investigations some to indicate is that for many error exceptions (though not all), an exception inside of a ${} will cause the remainder of the calling context to be terminated and it just silently move on. Is this a known phenomenona? A temporary bug that is meant to be fixed? I’m using an up-to-date version of AndroidStudio.
    😮 1
    a
    m
    +2
    • 5
    • 22
  • m

    Mostafa Fahimi

    03/28/2020, 7:28 AM
    Hi. We create a Coroutine Scope, and call a function inside launch. What's the difference between making that function "suspend" and "not suspend(regular)" ?!
    l
    z
    • 3
    • 4
  • b

    Bruno_

    03/28/2020, 3:21 PM
    I'm designing the app model (not necessarily the
    @Entity
    -ies) with the help of the room docs. The thing is that in
    one-to-many
    scenario the parent knows nothing about the children plus every child has only an ID of the parent. However I absolutely have to have an
    Ad
    as well as the list of application results (not just ids, whole objects) in
    AdEntry
    . Is it possible to do so in Room?
    j
    • 2
    • 8
  • k

    kevindmoore

    03/28/2020, 8:21 PM
    I’m in the process of trying to fully convert my project to androidx. Having a weird crash before my Activity even gets started: Caused by: java.lang.ClassNotFoundException: Didn’t find class “androidx.appcompat.R$drawable”
    t
    b
    • 3
    • 3
  • k

    kevindmoore

    03/28/2020, 8:24 PM
    I did upgrade to Kotlin 1.3.70
    i
    m
    • 3
    • 2
  • j

    Jaxon Du

    03/29/2020, 7:49 AM
    Need advice on what to focus. I have developed some iOS apps and just recently learning Android dev. I have learn the basic (and glance through example apps) of Kotlin, Coroutines, Flow, Multiplatform, Ktor, Jetpack LiveData, Navigation, ViewModel, Fragment etc, and understand what stacks are required for modern Android app. The next step for my learning is develop an actual app and plan to master Android development by end of the year. I have more or less settle on Multiplatform with sqldelight, koin and kTor http client for the common codes. On the Android side, the choices are option A: current Jetpack components (Navigation, LiveData, ViewModel) or option B: Compose. Option A has many different pieces to learn and will take more time to master. The easy solution to to pick up both but it might be a waste as it appears that many Jetpack components such as Navigation, LiveData might not be even needed in Compose. On the other hand there are many tutorials, sample apps and architecture recommendation for the current Jetpack components, while its practically non existent for Compose (for example what’s the best stacks to use for an MVVM, MVI architecture Android app with Compose? Can one use Flow instead of LiveData?). Any advice, insights is much appreciated as I probably have some misunderstanding of modern Android stacks. Is knowledge of LiveData, Navigation, ViewModel etc essential for future (next year onwards) Android app development (assuming I do not need to support old Android codes)? If you’re planing a new Andoid app from scratch to start developing beginning 2021, what components/stacks would you use?
    :google: 1
    b
    j
    +2
    • 5
    • 8
  • g

    gsala

    03/29/2020, 11:39 AM
    What do people use to request runtime permissions through a suspending function? Simple google search shows this and this . Anyone has any opinions or alternatives worth considering?
    l
    • 2
    • 2
  • j

    Joey

    03/30/2020, 2:14 AM
    App crashes when doing
    class MainActivity : AppCompatActivity() {
        companion object {
            init {
                System.loadLibrary("encrypt")
            }
        }
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            tv_cipher.text = encryptString("test")
        }
    
        external fun encryptString(plaintext: String): String
    }
    Anything wrong? Library is already inside their respective architectures under
    src/main/jniLibs/<archi>
    :google: 3
    :stackoverflow: 2
    t
    v
    • 3
    • 6
  • g

    Gaurav

    03/30/2020, 12:43 PM
    Any one doing ui testing? I am trying to run emulator on jenkins(aws ec2) , it giving me error also can we run x86 emulator on jenkins?
    w
    • 2
    • 6
  • j

    Jordan Carlyon

    03/30/2020, 6:27 PM
    Hello. I am having some trouble figuring out what is going on in this Android sample Specifically
    sealed class Result<out R>
    From the generics documentation
    The general rule is: when a type parameter 
    T
     of a class 
    C
     is declared out, it may occur only in out-position in the members of 
    C
    , but in return 
    C<Base>
     can safely be a supertype of 
    C<Derived>
    .
    In “clever words” they say that the class 
    C
     is covariant in the parameter 
    T
    , or that 
    T
     is a covariant type parameter. You can think of C as being a producer of `T`'s, and NOT a consumer of `T`’s.
    So I can see that type parameter
    R
    of class
    Result
    can only be returned by
    Result
    ,
    Error
    and
    toString
    but what is
    R
    ? Is my assumption correct? I can see here that it is a callable reference
    References to functions, properties, and constructors, apart from introspecting the program structure, can also be called or used as instances of function types.
    The common supertype for all callable references is 
    KCallable<out R>
    , where 
    R
     is the return value type, which is the property type for properties, and the constructed type for constructors.
    But I am not sure what that is or why it matters here. Is this applicable to this sealed class or is this not considered a callable reference since it is a sealed class? Is the constructor the callable reference and then the return type is
    Change<R>
    ?
    i
    • 2
    • 3
  • a

    Andy Gibel

    03/30/2020, 10:19 PM
    Hi all - anyone have some prod experince with MVI and Unidirectional data flow with Kotlin Flow/Coroutines?
    t
    • 2
    • 12
  • s

    Sagar Suri

    03/31/2020, 4:17 AM
    What is the point of generating a separate keystore for a debug build? I found this in a open source project. Doesn’t android studio generates a
    debug.keystore
    by default for a debug build?
    signingConfigs {
            debug {
                storeFile file('keystore/debug.jks')
                storePassword 'android'
                keyAlias = 'android'
                keyPassword 'android'
            }
        }
    l
    • 2
    • 3
  • r

    Reprator

    03/31/2020, 11:48 AM
    Hi Mates, i need a help in writing unit test cases for a top level function, if possible can you guys help me to get through this, Stackoverflow question , thanks in advance
    a
    • 2
    • 11
  • s

    SrSouza

    03/31/2020, 1:58 PM
    Hi folks, anyone that uses moshi and moshi codegen was able to update to Kotlin 1.3.70 ? I'm getting a compilation fail on
    compileDebugJavaWithJavac
    with
    no source files
    message, When a downgrade to Kotlin 1.3.50 its working.
    a
    z
    • 3
    • 3
  • j

    Joey

    04/01/2020, 6:59 AM
    Hi guys! Anyone implemented an architecture in their own library? I wonder where can i find examples of library with MVVM or MVP architecture? Thanks!
    :google: 3
    a
    • 2
    • 3
  • o

    Ofir Bar

    04/01/2020, 9:07 AM
    Is there a way to shorthen the part in red? (I know that in Swift there is something) Following line I am calling an enum which is inside a companion object in my ViewModel. This lne is called from my Activity:
    a
    l
    • 3
    • 3
  • m

    MartinZaubitzer

    04/01/2020, 11:59 AM
    Hi people, maybe someone can help me explain coroutines for my use case: I am developing a BLE communication protocol which includes messages that receive a custom answer from the peripheral. Now I would like to use coroutines and channels to make a queue of messages to send and only send the next message after a successful response. I am struggling to understand how I can await the result of the ble callback since it is not a function that returns anything. Thanks in advance!
    g
    • 2
    • 7
  • m

    mathew

    04/01/2020, 1:03 PM
    Hi All, I am new to Kotlin and started android development with Kotlin. Can you guys tell me what is the advantage of using Kotlin over Java?
    m
    a
    d
    • 4
    • 6
  • t

    Tim

    04/01/2020, 1:25 PM
    Hello, sometime recently i believe i came across a library which had a logging feature where instead of using
    Log.d(TAG, "something")
    , you could just do
    d { "something" }
    and the logger would automatically figure out what class and method its in. Does anyone either happen to know this library or know how i could implement that myself?
    c
    j
    d
    • 4
    • 12
  • a

    Andy Gibel

    04/01/2020, 1:52 PM
    Does anyone else have near constant problems with Viewbinding/navigation components and Android Studio not recognizing the generated Kotlin code?
    c
    i
    • 3
    • 20
  • g

    gouravkundu

    04/01/2020, 4:47 PM
    Can we use DialogFragment or BottomSheetDialogFragment with constructor injection using FragmentFactory.
    :yes: 1
    v
    • 2
    • 1
  • m

    Mirmukhsin Sodikov

    04/01/2020, 7:05 PM
    Hi, can someone explain why IntelliJ is giving an error like that? IntelliJ is saying that
    Variable mOnClickListener must be initialized
    and underlines the
    mOnClickListener
    inside the
    init
    statement. I have been doing the same thing in Java and it didn’t say anything like that. Am I missing something here ? EDIT : I am trying to make a custom layout here. I have been doing this in Java all the time - assigned
    OnClickListener
    to a private variable and then setting it to a button in the constructor.
    class CustomLayout(context: Context) : FrameLayout(context) {
    
        companion object {
            const val RESOURCE = R.layout.layout_custom
        }
    
        init {
            LayoutInflater.from(context).inflate(RESOURCE, this)
            // IntelliJ underlined `mOnClickListener` here and it says : "Variable mOnClickListener must be initialized"
            btnSend.setOnClickListener(mOnClickListener) 
        }
    
        private val mOnClickListener = OnClickListener { context.toastInfo("Info") }
    }
    Java version of the code which works fine
    public class CustomLayout extends FrameLayout{
    
         public CustomLayout(){
              // inflating the xml layout
              ...
              btnSend.setOnClickListener(mOnClickListener);
         } 
    
         private OnClickListener mOnClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                // do something
            }
        };  
    
    }
    a
    • 2
    • 5
  • t

    Tash

    04/02/2020, 7:01 PM
    Oh, oops I read your earlier message and thought you meant “low memory issues” 😄
    k
    • 2
    • 3
  • l

    lawlorslaw

    04/02/2020, 7:04 PM
    In Kotlin you can have a file that contains multiple class or interface definitions. when this is the case what name do you give to your file? For example if you had Dagger in your project and you wanted to group the
    @Component
    and
    @Module
    defined in the same file what would you name that file?
    g
    i
    • 3
    • 2
  • t

    Travis Griggs

    04/03/2020, 12:20 AM
    I want to have something occur at a 5 second tick. What is the kotlin/Android idiomatic way to do this? I’m currently doing:
    this.timer = Timer()
    this.timer?.scheduleAtFixedRate(timerTask { simulate() }, 0L, 5000L)
    I’m not a fan of this solution, because
    this
    isn’t what I expect this to be in that case. But when in rome, I guess? Or is there a different more modern idiomatic way to cause a real closure to tick at a rate?
    t
    • 2
    • 1
  • t

    Tim Malseed

    04/03/2020, 1:06 AM
    Anyone familiar with the new scoped storage rules? https://developer.android.com/training/data-storage/shared/media#remove-item I’m attempting to delete a file like so:
    context.contentResolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, "${MediaStore.Audio.Media._ID} = ?", arrayOf(id.toString()))
    Supposedly, if I don’t have permission, this should throw a
    RecoverableSecurityException
    on Android Q, and I should be able to use an IntentSender to have the user grant permission. Instead, I just get a result of
    0
    from the
    delete()
    call, meaning no files were deleted. Any ideas?
    t
    • 2
    • 3
  • j

    Jabez Magomere

    04/03/2020, 8:30 AM
    I want to dynamically include or exclude a field in a kotlin class based on certain conditions at run time before making a POST request using Retrofit and Gson, anyone has ideas on how to achieve this dynamically? I've tried using the expose annotation but it can't accept run time variables.
    w
    • 2
    • 6
  • m

    myanmarking

    04/03/2020, 11:09 AM
    when using MAterialToolbar, how to set it's style in themes?
    <item name="toolbarStyle">@style/Widget.Toolbar</item>
    and then
    <style name="Widget.Toolbar" parent="Widget.MaterialComponents.Toolbar">>
    does nothing. does any1 have a clue ?
    a
    • 2
    • 6
Powered by Linen
Title
m

myanmarking

04/03/2020, 11:09 AM
when using MAterialToolbar, how to set it's style in themes?
<item name="toolbarStyle">@style/Widget.Toolbar</item>
and then
<style name="Widget.Toolbar" parent="Widget.MaterialComponents.Toolbar">>
does nothing. does any1 have a clue ?
a

antoniomarin

04/03/2020, 11:39 AM
I don’t think you need any parents, just make sure you wrap it in the
AppBar
View XML:
<com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="?attr/actionBarSize"
        style="@style/Toolbar"
        />
Styles:
<style name="Toolbar">
...
</style>
m

myanmarking

04/03/2020, 11:40 AM
this new theming is weird and confusing, but i found the problem. It works as expected. i was setting textColor in the style, but it must be inside another textAppearance style
thanks for your help anyway 😛
a

antoniomarin

04/03/2020, 11:41 AM
Yep I agree with you, we use various components and finding right parent can be a bit tricky, you need to dig through components source code…
m

myanmarking

04/03/2020, 11:42 AM
you can also use layout inspector, click on the widget and check theme/style inheritance. works great
a

antoniomarin

04/03/2020, 11:43 AM
Oh ye, thanks for the tip! 😄
View count: 7