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

    Jan Lund

    10/01/2020, 5:20 PM
    Is there any good pattern for keeping track of the latest value of a DataStore preference without having to go via Flow and asynchronicity, for example for keeping track of a boolean value at various places without having to go through coroutines? Like observing all changes and updating a property which can be used in if/else in various parts of the code base? Code examples? Or is it a bad idea altogether?
    i
    c
    • 3
    • 8
  • c

    Christopher Elías

    10/02/2020, 1:42 PM
    Hello you all 🙋‍♂️, What do you think about this approach? On an Android project with a modularization per feature architecture, would you create a retrofit instance per each feature? Isn't this very costly? My friends and I are currently working on this kind of architecture, and we are in the stage of integrate the REST API. We are trying to isolate as much as we can every feature. But should we create a retrofit instance on each feature module that needs to call a service or should we have another module let's say "data" and handle all the retrofit thing there? What would you do?
    t
    c
    i
    • 4
    • 9
  • z

    zsperske

    10/02/2020, 5:22 PM
    If Fragment's
    onStart
    is always called (even when you've backgrounded the app and returned) what is its purpose? How do you do something only once after a fragment's view is created?
    :stackoverflow: 1
    j
    • 2
    • 4
  • k

    Kavita

    10/02/2020, 5:26 PM
    Hello everyone, I am facing one issue related to test cases. My Android project has more than 250 tests. Most of them include API mocking & some of them are unit tests. In Android Studio when I run the individual test class, all tests in that class succeed. But when I run the entire test package(altogether), some of the tests fail randomly. The project has the unit & espresso tests with
    MockWebSerever
    &
    Awaitility
    to handle API mocking & async operation. The
    .gradle
    file also has Android Orchestrator & clearPackageData declared. All the tests are independent. Still, the issue persists. Can someone help me to fix this issue? Please let me know if you need more details about tests & Android version.
    j
    f
    e
    • 4
    • 19
  • a

    Antoine Gagnon

    10/02/2020, 6:24 PM
    Hello everyone, I’m having some issues trying to set a special autoSizing behaviour for a TextView. My font size is currently 26sp, I want my size to reduce down to 22sp at most to try to fit my text on 2 lines. But if even with 22sp, my text is too long, I want it to ignore the two lines restriction and stay at 22sp but on more than 2 lines. Is there any way to achieve this?
    :stackoverflow: 1
    :google: 1
    f
    • 2
    • 2
  • n

    Nikola Milovic

    10/03/2020, 6:59 AM
    Hey guys, I've been overwhelmed by ContentProviders and FIleProviders and need some help. I have an image stored on the emulators SD card in the /Pictures direectory, the files path is like this
    /storage/1018-2710/Pictures/Sarx7IIJi-o.jpg
    , but when I try to share the image I get an error saying
    Failed to find configured root that contains /storage/1018-2710/Pictures/Sarx7IIJi-o.jpg
    . I have configured everything from the docs , but I cannot figure out which combination I need for my file-paths.xml file. I am currently using this
    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="<http://schemas.android.com/apk/res/android>">
        <external-path name="external_files" path="/" />
    </paths>
    But this is the wrong location for the files I need. Basically, I am asking which one of these do I need to be able to access files from the MediaStore.Images ie /Pictures directory. Thank you! I tried googling and reading the docs but that got me to this point.
    :stackoverflow: 2
    :google: 2
    • 1
    • 1
  • f

    fummicc1

    10/03/2020, 9:00 AM
    [SOLVED] Hello everyone. I am new to Android. I am facing an error 
    A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
     when using Room framework(may be library?). I make an application to practice 
    Room
     , referring to this official course. I create
    Entity
    ,
    DAO
    ,
    Database
    ,
    Repository
    ,
    ViewModel
    and
    Converter
    to persist
    Date
    in SQLite. almost all things are done. but when I try to debug my application from Android Studio, I got this error
    A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
    (please look at the attached image). If anyone else can help me, this repository on GitHub can reproduce this issue so please check it. Please tell me how to solve this problem. P.S this is more detail error description.
    * What went wrong:
    Execution failed for task ':app:kaptDebugKotlin'.
    > A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
       > java.lang.reflect.InvocationTargetException (no error message)
    n
    • 2
    • 4
  • d

    Daniel

    10/03/2020, 2:13 PM
    I'm following the recommended Codelab for learning how to use Room, and they suggest copy and pasting this code.
    // Annotates class to be a Room Database with a table (entity) of the Word class
    @Database(entities = arrayOf(Word::class), version = 1, exportSchema = false)
    public abstract class WordRoomDatabase : RoomDatabase() {
    
       abstract fun wordDao(): WordDao
    
       companion object {
            // Singleton prevents multiple instances of database opening at the
            // same time. 
            @Volatile
            private var INSTANCE: WordRoomDatabase? = null
    
            fun getDatabase(context: Context): WordRoomDatabase {
                val tempInstance = INSTANCE
                if (tempInstance != null) {
                    return tempInstance
                }
                synchronized(this) {
                    val instance = Room.databaseBuilder(
                            context.applicationContext,
                            WordRoomDatabase::class.java, 
                            "word_database"
                        ).build()
                    INSTANCE = instance
                    return instance
                }
            }
       }
    }
    The code contains a number of things I don't understand (
    @Volatile
    ,
    synchronized
    ), and Android Studio warns that
    synchronized
    is a Kotlin internal with no stability guarantees. Copying in something I don't understand which uses internal APIs I don't understand doesn't feel like a great idea. Is there an alternative?
    k
    • 2
    • 2
  • a

    Ayden

    10/03/2020, 2:34 PM
    Hi guys. I have a question, why my data will update and display on the RecyclerView in real-time even though my code does not consist of
    observe()
    to observe the ViewModel? I bit confuse.
    d
    • 2
    • 7
  • y

    Yamila Gammeri

    10/05/2020, 12:02 AM
    Hey everyone. I’m using Jetpack Datastore proto models, how do I clear/remove a persisted datastore? E.g. removing user credentials on logout
    t
    • 2
    • 2
  • t

    Tim Malseed

    10/05/2020, 12:51 AM
    I’ve tried changing the configuration, like so:
    implementation(project(":ktaglib:lib", { "release" }))
    But this doesn’t seem to resolve the problem
    t
    • 2
    • 2
  • r

    Rajsingh Techm18

    10/05/2020, 7:17 AM
    Hi I am trying to create a ViewPager with indicator tabs using AndroidCompose , can any one help
    a
    • 2
    • 2
  • a

    Archie

    10/05/2020, 2:01 PM
    Does requesting for
    ACCESS_FINE_LOCATION
    and
    ACCESS_COARSE_LOCATION
    count as accessing
    BACKGROUND_LOCATION
    ? I have an app which request both of those permissions for
    Google Maps
    and I am receiving warnings about
    BACKGROUND_LOCATION
    after uploading the apk in playstore. I don't used
    FusedLocationService
    in the app as well just the google maps itself so I'm really confused about the warning presented ng
    Google Play
    . Can anyone shed a light on this? Is there something I should be doing?
    a
    • 2
    • 9
  • t

    tseisel

    10/05/2020, 4:14 PM
    Am I the only one noticing that there is no longer a documentation for Kotlin Android Extensions on Kotlin's official site? Especially on how to configure
    androidExtensions
    block ?
    v
    s
    • 3
    • 3
  • b

    brandonmcansh

    10/06/2020, 12:52 AM
    Good evening everyone, I'm currently trying to migrate a legacy app using v4 support libraries to AndroidX and update AGP and Kotlin to 1.4 and I'm hitting a cryptic crash during runtime that I haven't been able to isolate or track down yet. Has anyone come across this before?
    g
    • 2
    • 4
  • c

    Corey Lanier

    10/06/2020, 3:20 AM
    Hi all, trying to add multiple build environments to my project via env files (containing api base urls, secrets and such). Coming from Javascript and unsure how to do this in in Kotlin for an android project.
    a
    • 2
    • 14
  • c

    Chris Fillmore

    10/07/2020, 2:10 AM
    Hi folks, this is not really a Kotlin question but I hope you don’t mind. I am implementing a ViewModel for the first time as per https://developer.android.com/topic/libraries/architecture/viewmodel#implement Looking at the code example here (from above link):
    class MyViewModel : ViewModel() {
        private val users: MutableLiveData<List<User>> by lazy {
            MutableLiveData().also {
                loadUsers()
            }
        }
    
        fun getUsers(): LiveData<List<User>> {
            return users
        }
    
        private fun loadUsers() {
            // Do an asynchronous operation to fetch users.
        }
    }
    It is not clear how
    loadUsers()
    could be implemented, as
    MyViewModel
    accepts no dependencies. In particular, if I want to instantiate MyViewModel like so:
    val model: MyViewModel by viewModels { SavedStateViewModelFactory(this.application, this) }
    it’s not clear to me how I could pass dependencies (like “MySomethingRepository”) to the view model
    a
    • 2
    • 1
  • c

    Chris Fillmore

    10/07/2020, 2:11 AM
    So more specifically, my question is, can I use
    androidx.activity
    function
    viewModels()
    and pass dependencies to e.g.
    MyViewModel
    ?
    a
    • 2
    • 11
  • c

    coroutinedispatcher

    10/07/2020, 6:12 AM
    Hello. What can I use to decode a .wav file (Frequency Shift Keying)? Aparently reading the bytes normally from the file is giving me around 2mln bytes which I don't think it's the right way to go. Did google a little but didn't find any good late tool. Any help?
    :google: 2
    :stackoverflow: 1
    • 1
    • 1
  • d

    Dmitry Khasanov

    10/07/2020, 8:24 AM
    Hi guys, can anyone help me to understand if is it safe to have kotlin
    1.4.x
    in some of dependencies (latest okhttp library for example) and
    1.3.72
    in the project and in some other dependencies too?
    j
    • 2
    • 5
  • h

    hisham bin awiad

    10/07/2020, 9:24 AM
    :google: 1
    :stackoverflow: 1
    n
    • 2
    • 2
  • g

    Geert

    10/07/2020, 12:55 PM
    Is it possible to get to this screen programmatically?? I found
    val intent = Intent(Settings.ACTION_MANAGE_DEFAULT_APPS_SETTINGS)
    startActivity(intent)
    but the user still needs to click a few times and they probably don’t kno where. I want them to set it to always when they launch the app the first time
    :google: 1
    :stackoverflow: 3
    • 1
    • 1
  • p

    Pau

    10/07/2020, 1:23 PM
    Hi guys, what is your view about Google-Oracle fight? Which are the consequences if Google loses?
    :google: 7
    d
    • 2
    • 5
  • r

    Robert Menke

    10/07/2020, 2:39 PM
    Hey, I have a use case where I’d like to encrypt the output of
    MediaMuxer
    in memory before writing to disk. The general approach is: • Create a
    MemoryFile
    • Create a
    CipherInputStream
    from the `MemoryFile`’s
    InputStream
    • Give the `MemoryFile`’s
    FileDescriptor
    to the
    MediaMuxer
    constructor • Create a
    FileOutputStream
    from the
    CipherInputStream
    Right now I’m having to use reflection to get the file descriptor from
    MemoryFile
    and I’m curious why the getter is unsupported for app usage https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/MemoryFile.java#230.
    :stackoverflow: 1
    :google: 1
    d
    • 2
    • 2
  • s

    Slackbot

    10/07/2020, 3:22 PM
    This message was deleted.
    👍 1
    a
    • 2
    • 1
  • j

    Juan Rodríguez

    10/07/2020, 3:28 PM
    Hello! I have a question about the SpeechRecognizer, and I don't know if anyone is familiar with it or has gone through the same problem. What I'm trying to do is that when pressing a button it starts recording, and when the button is released it stops recording. I have tried calling the
    stopListening()
    method as well as the
    cancel()
    method, but they are both ignored and nothing happens. I don't know if anyone has done this before, but I appreciate any help
    :stackoverflow: 1
    :google: 1
    • 1
    • 1
  • s

    Slackbot

    10/07/2020, 8:24 PM
    This message was deleted.
    :stackoverflow: 2
    :google: 2
    i
    • 2
    • 2
  • e

    ed_mayen

    10/08/2020, 7:21 PM
    Hi guys! Anyone know of a way to disable a click on the first position of the recyclerview? I got a recyclerview with implementation of onClickListener but I need to disable the click only for the first position, anyone know how to do it?
    :stackoverflow: 2
    m
    • 2
    • 2
  • g

    ghosalmartin

    10/09/2020, 7:09 AM
    bit more jvm than kotlin really, but would have a million of instances of data classes bloat an apps memory size
    z
    • 2
    • 2
  • a

    Ayden

    10/09/2020, 10:14 AM
    I have a
    ViewHolder
    class which in charges of populating the data to the
    quote_list.xml
    . I create a
    setOnClickListener
    on the ViewHolder which would call a
    QuoteFragment
    that populated the relevant data into it. May I know how to populate the data from the
    ViewHolder
    to the
    QuoteFragment
    ?
    inner class QuoteViewHolder(private val bindingQuoteListBinding: QuoteListBinding) :
        RecyclerView.ViewHolder(bindingQuoteListBinding.root) {
        fun bind(quote: Quote) {
            // Assign data to the textview
            bindingQuoteListBinding.tvQuote.text = quote.quote
            bindingQuoteListBinding.tvAuthor.text = quote.author ?: "None"
    
            bindingQuoteListBinding.cardQuote.setOnClickListener {
                val activity = it.context as AppCompatActivity
                val fragment = QuoteFragment()
                fragment.show(activity.supportFragmentManager, "TAG")
            }
        }
    }
    a
    m
    a
    • 4
    • 4
Powered by Linen
Title
a

Ayden

10/09/2020, 10:14 AM
I have a
ViewHolder
class which in charges of populating the data to the
quote_list.xml
. I create a
setOnClickListener
on the ViewHolder which would call a
QuoteFragment
that populated the relevant data into it. May I know how to populate the data from the
ViewHolder
to the
QuoteFragment
?
inner class QuoteViewHolder(private val bindingQuoteListBinding: QuoteListBinding) :
    RecyclerView.ViewHolder(bindingQuoteListBinding.root) {
    fun bind(quote: Quote) {
        // Assign data to the textview
        bindingQuoteListBinding.tvQuote.text = quote.quote
        bindingQuoteListBinding.tvAuthor.text = quote.author ?: "None"

        bindingQuoteListBinding.cardQuote.setOnClickListener {
            val activity = it.context as AppCompatActivity
            val fragment = QuoteFragment()
            fragment.show(activity.supportFragmentManager, "TAG")
        }
    }
}
a

alex_vinz

10/09/2020, 11:52 AM
If I understood correct, better pass cosure or juat onClikcListener from fragment -> adapter -> viewholder. and trigger it from VH
val onQuoteClick: (Quote) -> Unit
m

Matthew Laser

10/09/2020, 1:09 PM
this is what i tend to do as well, just passed down from the fragment when instantiating the adapter
a

Afzal Najam

10/09/2020, 5:25 PM
Lol, there's this loooooooooooong StackOverflow thread about this and what approaches different people like to take: https://stackoverflow.com/questions/29424944/recyclerview-itemclicklistener-in-kotlin I updated the question to have the current popular approach too. If you really need to handle the click event in the Activity/Fragment, you can pass the function all the way down to the ViewHolder. Or if you don't need access to the Activity/Fragment (maybe in case of using the Navigation library), you can just implement
View.OnClickListener
in the ViewHolder and use
itemView.setOnClickListener(this)
in the
init
block
View count: 6