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

    dewildte

    04/03/2020, 3:51 PM
    Say I have Views A, B and C. A is baselined to C. C is then set to GONE. Is there a way in XML to change A's baseline alignment to B in that scenario? (edited)  Like a 
    app:gone_baseline="some_other_view_than_this_one"
    c
    e
    • 3
    • 7
  • e

    Ellen Spertus

    04/03/2020, 10:39 PM
    How do I create a
    ViewModel
    class with a constructor that takes parameters? I found this advice, but there’s a comment saying it’s deprecated. https://www.albertgao.xyz/2018/04/13/how-to-add-additional-parameters-to-viewmodel-via-kotlin/
    :stackoverflow: 1
    m
    • 2
    • 1
  • s

    Souhail Marghabi

    04/04/2020, 8:32 AM
    Greetings, I am not sure if it is the right if it is the right channel, but I do hope some guidance and/or help. I have recently starting Using Glide to load Images from a REST API for a new project I am working and I have become somewhat desperate with an issue I am facing at the moment. I am trying to load images from an existing API, the issue is that the images come as encrypted Bytearray and cannot be read if not decrypted prior to being loaded to the imageView. The flow is as follows: LoadImage(id) -> OutputByteArray -> DecryptAES() -> assign decrypted bytearray/bitmap to imageView. I tried to look for tutorials and examples in Kotlin to do this step, but could not find any relevant sources(I am aware of ModelLoaders and DataRetrievers), but I could not understand how I could add that simple step of Decryption step through Glide
    // RecyclerViewListItem.kt
    
    val encryptedImageEndpoint = "API_URL"
      val glideUrl = GlideUrl(encryptedImageEndpoint) { mapOf(Pair("Authorization", "Bearer $testToken")) }
      
      Glide.with(this.containerView).load(glideUrl).signature(ObjectKey(imageID))
                        .transition(DrawableTransitionOptions.withCrossFade()).thumbnail(0.25f)
                   .apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.AUTOMATIC).skipMemoryCache(true).override(selfReference.snapshotImage.width, selfReference.snapshotImage.height)
                                .placeholder(R.drawable.empty_result)
                        ).into(this.itemView.snapshotImage)
    
    //before loading to imageVIiew I need the following to be done with the API Call response: val decryptedByteArray = CryptoCbc.decryptAesCBC(byteArrayFromResponse, sharedSecret)
    p
    • 2
    • 2
  • h

    henrikhorbovyi

    04/04/2020, 7:04 PM
    Hey all, I have some logic that executes inside koltin [buildSrc] module, but this logic depends on BuildConf.DEBUG. And I can't find BuildConfig class inside this module. How can I achieve this? Thank you
    w
    • 2
    • 12
  • j

    J6ey

    04/05/2020, 7:40 AM
    Hey guys I am trying to open a pdf file from the Downloads folder, but when I try to it closes immediately.
    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "la.pdf");
    
    Uri pdfUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", file);
    Intent intent = new Intent(Intent.ACTION_VIEW, pdfUri)
    .setDataAndType(pdfUri, "application/pdf")                   
    .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    startActivity(intent);
    file.exists()
    shows that the file exists. I am able to locate and open the file in the Download folder, but just not by code. Any idea?
    :stackoverflow: 1
    p
    d
    • 3
    • 20
  • r

    Remy Benza

    04/05/2020, 3:05 PM
    Quick question, I got two lists. List A are local photos (Android room database), List B are photos from the network. I want to compare both lists and show a 'favorite' icon if an item from List A is present in List B
    b
    • 2
    • 7
  • a

    am414

    04/05/2020, 5:08 PM
    anyone knows how to restart app programaticlly in android 10 ?? pending intent + alarm maneger didn't work
    b
    • 2
    • 2
  • s

    Slackbot

    04/05/2020, 7:30 PM
    This message was deleted.
    i
    r
    • 3
    • 3
  • a

    Alexander Suraphel

    04/05/2020, 8:18 PM
    https://stackoverflow.com/questions/61048912/is-it-possible-to-make-a-room-sqlite-column-not-null-while-the-entity-field-is-n
    r
    • 2
    • 1
  • r

    rkeazor

    04/05/2020, 10:07 PM
    sorry to go off topic for a sec, Has anyone notice any performance issues with AGP 3.6.2
    p
    w
    • 3
    • 4
  • s

    Slackbot

    04/05/2020, 11:29 PM
    This message was deleted.
    a
    • 2
    • 1
  • e

    Ellen Spertus

    04/06/2020, 8:46 PM
    I am adapting the Android Room with a View tutorial to my domain. As shown in the picture, I get an
    Unresolved reference: Callback
    error in the expression
    ContactDatabase.Callback
    . Why? As shown,
    ContactDatabase
    extends
    RoomDatabase
    , and
    RoomDatabase.Callback
    is defined.
    @Database(entities = arrayOf(ContactEntity::class), version = 1)
    abstract class ContactDatabase : RoomDatabase() {
        abstract fun contactDao(): ContactDao
        lateinit var callback: RoomDatabase.Callback
    
        private class ContactDatabaseCallback(
            private val scope: CoroutineScope
        ) : ContactDatabase.Callback() {  <-- Error on this line
    t
    • 2
    • 7
  • d

    Deepti M

    04/06/2020, 9:40 PM
    I want to create multiple replicas of a project with minor changes (like db filters) in each. For the same I created a library project and want to use its activities in child-replicas. But as soon as I am trying to inherit the parent activity in replica module I receive following error on its... • Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath: class com.alivewallpaper.replicantlib.MainActivity, unresolved supertypes: com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener Can't we inherit library activities?
    g
    • 2
    • 2
  • v

    vinay

    04/07/2020, 6:01 AM
    Is there a way to force stop JiT compilation for your app, or force AoT compilation?
    🇳🇴 2
    m
    d
    • 3
    • 2
  • i

    itnoles

    04/07/2020, 8:02 PM
    is this is a bug that
    androidExtensions {
        features = ["parcelize"]
    }
    still generating synthetic properties in Kotlin 1.3.71?
    j
    j
    d
    • 4
    • 6
  • j

    J6ey

    04/08/2020, 9:15 AM
    Constraintlayout inside Framelayout a red flag? 🤔
    :google: 1
    :stackoverflow: 1
    l
    w
    a
    • 4
    • 8
  • s

    SrSouza

    04/08/2020, 2:48 PM
    Hi folks, anyone that was able to use constraint layout 2.0.0-beta4 in the editor of Android Studio 4.1 Canary 4? I'm getting a render error
    l
    • 2
    • 2
  • l

    Lucas Jesus

    04/08/2020, 9:19 PM
    Do anyone knows how can I maintain a fragment instance after asking permission? If I deny or allow the required permission, the activity is recreated and the fragment which I asked the permission dies
    :google: 1
    :stackoverflow: 1
    d
    • 2
    • 1
  • m

    Michael Pohl

    04/09/2020, 6:01 PM
    Hi all, I’ve worked on a project where we used a BaseFragment that looked like this:
    abstract class ViewModelFragment<VM : BaseViewModel>(@LayoutRes val layout: Int, private val viewModelClass: KClass<VM>) :
        BaseFragment() {
    
        open lateinit var viewModel: VM
    
        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
            viewModel = getViewModel(viewModelClass)
            return inflater.inflate(layout, container, false)
        }
    }
    The idea was to remove as much boilerplate noise in the fragment classes as possible. This project also used
    Koin
    for DI, this class uses
    Koin's
    getViewModel()
    to set the viewModel. What I don’t like about this approach is that subclasses of this have a constructor that looks like this:
    class AudioPlayerFragment : ViewModelFragment<AudioPlayerViewModel>(R.layout.fragment_audio_player, AudioPlayerViewModel::class)
    As you can see, for this to work, you need a type annotation and still have to hand in the KClass type, which is just ugly. So I’m wondering if there is any way to get this to just look like this:
    class MyFragment<MyViewModel> : ViewModelFragment(myLayout) {}
    I understand that there is a limitation as to what Kotlin can do with generics and that I’m basically looking for what `reified`functions can do, but on a class, and that that’s no new question. I was hoping to find a solution like this here: https://stackoverflow.com/a/48398303/8746644 But I can’t figure out a way that would work with Fragments and sub classes . I could also see writing a custom
    getViewModel
    function to deal with the type, but I don’t know how. Does anybody have a suggestion how I could achieve what I want in a reasonable way?
    w
    • 2
    • 2
  • j

    Joan Colmenero

    04/10/2020, 9:01 AM
    Guys I have a question, is still a good idea do apps for Tablets? I've been reading and Google is investing on Chrome OS since they say is better than do android tablet apps. I'd like to do a tablet app but I do not know if do it with Android would be the best idea. Could you recommend to me a tutorial to do tablet apps? Are you guys still doing apps for tablet?
    c
    • 2
    • 2
  • a

    Ananiya

    04/10/2020, 3:55 PM
    How to fetch data from website for example the numbers of affected person with covid-19 in use From worldmeters.info in Android studio using kotlin
    a
    c
    • 3
    • 4
  • a

    Ananiya

    04/10/2020, 5:34 PM
    how to generate new card view while i am touching button in kt
    s
    • 2
    • 29
  • m

    miqbaldc

    04/12/2020, 11:18 PM
    Anyone have experience regarding migration from Support Library to AndroidX? https://stackoverflow.com/questions/61179356/androidx-jetifier-unable-failed-to-transform-3rd-party-transitive-dependency-tha
    k
    c
    l
    • 4
    • 16
  • e

    eason

    04/13/2020, 7:47 AM
    reified T::class.java.simpleName return first capital word ex Float
    Float::class.java:simpleName return float
    is this normal or did i do something wrong?
    w
    • 2
    • 2
  • z

    zak.taccardi

    04/13/2020, 6:18 PM
    What’s the proper way to inject the
    CoroutineDispatcher
    for
    LifecycleCoroutineScope
    in production? Seems it’s hardcoded to
    Dispatchers.Main.immediate
    and
    SupervisorJob
    which is something I desire flexibility around https://developer.android.com/topic/libraries/architecture/coroutines#lifecyclescope
    w
    f
    r
    • 4
    • 117
  • s

    Santiago Oroz17

    04/13/2020, 10:23 PM
    Hi everybody! What do you recommend studying to work multi-modules with Dagger? Where more than one app will be used 🤯
    a
    • 2
    • 3
  • e

    Ellen Spertus

    04/13/2020, 10:46 PM
    I have a fragment whose behavior depends on the result of looking up the launching `Intent`’s extras in a
    RoomDatabase
    . I can’t access the database (or even the repository) directly from the fragment’s
    onStart()
    method, since database access is not allowed on the UI thread. What’s the right way for
    onStart()
    to initiate a database query on the
    IO
    thread and then a callback on the UI thread?
    r
    • 2
    • 3
  • m

    Mutlu Celep

    04/14/2020, 2:20 AM
    Hi y'all, I have a problem, so I asked in stackoverflow. Could you help me? Thank you https://stackoverflow.com/questions/61199571/how-to-test-lambda-func-with-mockito-on-android
    r
    r
    • 3
    • 9
  • j

    ja.son

    04/14/2020, 7:51 AM
    Hello, I am developing Android with Kotlin. I need a back-end, so I'm going to try ktor. There are many difficulties in using the ktor without back-end knowledge. Can you help me?
    r
    c
    • 3
    • 6
  • o

    Orhan Tozan

    04/14/2020, 1:17 PM
    When is an Android ViewModel's
    init {}
    called? I know that LiveData's only get initialized after observing them, but what about the init block? On Activity onCreate?
    a
    m
    +2
    • 5
    • 15
Powered by Linen
Title
o

Orhan Tozan

04/14/2020, 1:17 PM
When is an Android ViewModel's
init {}
called? I know that LiveData's only get initialized after observing them, but what about the init block? On Activity onCreate?
a

aipok

04/14/2020, 1:38 PM
It depends when you create it. The
init
will be called first time ViewModel is created. For example when it is being injected or when you create it from factory and it will not be called in case fragment get it as a shared instance.
o

Orhan Tozan

04/14/2020, 1:38 PM
I am using Koin, apparently init gets called lazily after first usage of viewmodel
a

aipok

04/14/2020, 1:41 PM
Then
init
will be called in the same method where you call it for the first time. In case it is in Activity:onCreate, then it will be called there.
o

Orhan Tozan

04/14/2020, 1:42 PM
Yes indeed, I was asking because my viewmodel right now only is used for its init block but it wasnt doing anything. I am now calling viewmodel.toString() in onCreate just so that it gets triggered.
It works now
a

aipok

04/14/2020, 1:45 PM
well, correctly would be to just assign the variable with
late init
in your activity using
get()
from Koin. Not sure that calling the viewModel.toString is a good idea, since some other developer could break it very easy, he might think that it is some leftover from debugging. I had such cases in past 😄
o

Orhan Tozan

04/14/2020, 1:46 PM
This is how I define a viewmodel in koin in activity
a

aipok

04/14/2020, 1:49 PM
you can define it as
private lateinit var viewModel: HomeViewModel

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
   viewModel = getViewModel<HomeViewModelUsingEngine>()
}
something like this should do the trick
m

Matt Thompson

04/14/2020, 3:43 PM
or move logic out of the init block and into a function that is explicitly called in onCreate - might be clearer
☝️ 2
o

Orhan Tozan

04/14/2020, 6:01 PM
I thought about that, something like an onStart() method, but I see alot of examples, including Google's, use the init block. So I thought it is better practice to do so myself.
b

Bruno_

04/15/2020, 8:23 AM
if you decompile the kotlin code with init
class Foo(private val string: String) {
    init {
        val a = 2 + 2
        println(a)
        println(string)
    }
}
you'll get the following thing
public final class Foo {
   private final String string;

   public Foo(@NotNull String string) {
      Intrinsics.checkParameterIsNotNull(string, "string");
      super();
      this.string = string;
      int a = 4;
      boolean var3 = false;
      System.out.println(a);
      String var5 = this.string;
      boolean var4 = false;
      System.out.println(var5);
   }
}
so init is basically a constructor, it's not lazy by any means
m

myanmarking

04/15/2020, 1:29 PM
init {} is not a viewModel thing, but kotlin's isnt it? Init is called just after constructor return
View count: 37