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

    ubu

    11/21/2019, 4:29 PM
    Hi guys! Is there a way on Android to convert to an emoji the following code convention: "😒omething:"? Couldn't find the answer.
    p
    • 2
    • 2
  • c

    Cyberpunk Keanu

    11/22/2019, 10:58 AM
    Anyone know how do I fix this? I'm receiving data in the detail activity using retrofit request, & send that data to the 4 tabs in my viewpager with View Model Now when the Activity loads, it has to also load the viewpager along with the first fragment which is displayed in the start. But problem is, making the request call & get the data, pass it to viewmodel, get data from the viewmodel takes some time I guess. Until then, the first fragment is already loaded without the items in my recyclerview. How do I automatically refresh the first fragment in the viewpager when my data has been fetched?
    2019_11_22_16_19_11.mp4
    s
    s
    m
    • 4
    • 6
  • d

    Duchynko

    11/22/2019, 1:00 PM
    Hello guys. I have a problem with my local room database. Domain model
    @Entity(tableName = "students")
    data class Student(
        @PrimaryKey(autoGenerate = true)
        val id: Int? = null,
        var studentName: String,
        val studentId: String,
        var purchaseDate: String,
        val comment: String
    )
    DAO
    @Dao
    interface StudentDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun upsert(student: List<Student>)
    
        @Query("select * from students")
        fun getStudents(): LiveData<List<Student>>
    }
    Repository methods for upserting and getting List of Students
    private fun persistFetchedStudents(fetchedStudents: StudentsResponse) {
        GlobalScope.launch(<http://Dispatchers.IO|Dispatchers.IO>) {
            Log.i("StudentRepositoryImpl", "Called from persistFetchedStudents: fetchedStudents.students.size = " + fetchedStudents.students.size)
            studentsDao.upsert(fetchedStudents.students)
        }
    }
    Log -> fetchedStudents.students.size = 140
    private fun isFetchStudentNeeded(): Boolean {
        Log.i("StudentRepositoryImpl", "Called from isFetchStudentNeeded: studentsDao.getStudents().value = " + studentsDao.getStudents().value)
        return studentsDao.getStudents().value.isNullOrEmpty()
    }
    Log -> studentsDao.getStudents().value = null Is there anything I'm doing wrong? I can't see any issue myself. Thanks for any help 🙂
    g
    d
    • 3
    • 9
  • s

    Soumik

    11/23/2019, 7:13 PM
    Hello everyone, Can you guys help me to find the solution of this problem: https://stackoverflow.com/questions/59009872/how-to-rename-the-key-of-a-json-response-dynamically-in-retrofit2-android Sorry for providing external link, but I really got stuck at this.
    d
    d
    • 3
    • 4
  • v

    vpriscan

    11/24/2019, 12:18 PM
    What is now the preferred way to do view binding? Kotlin Android Extensions still or?
    l
    g
    +5
    • 8
    • 9
  • d

    dave08

    11/24/2019, 5:22 PM
    Hi! Does it make sense to do
    lifecycleScope.launch { }
    in a
    LifecycleService
    when handling intents, or will it leak?
    l
    • 2
    • 1
  • d

    dave08

    11/24/2019, 5:23 PM
    It seems like
    runBlocking {}
    isn't possible anymore, since you can't use the
    lifecycleScope
    with it...
    l
    • 2
    • 8
  • m

    Md Razon Hossain

    11/25/2019, 1:59 AM
    In mutableLiveData<Int> , i am pushing USER_NOT_LOGGED_IN (==4) value in the starting of app from sharedpref. Still even these lines are executed, (I tested it by debugging), I am getting the livedata value 1. What is I am missing here?
    a
    h
    • 3
    • 8
  • k

    Kstabks

    11/25/2019, 12:07 PM
    Hello everyone, has anyone of you tried to use an inline class with Room database? I mean to use such inline class as an entity property but seems to be not working. It is described here https://stackoverflow.com/questions/58203953/room-database-with-kotlin-inline-class-as-an-entity-field
    g
    • 2
    • 1
  • p

    petermonteer

    11/25/2019, 1:19 PM
    I'm moving away from using KotterKnife in my apps, since support and development was withdrawn a while ago. With ViewBinding still in Canary, what alternatives are you using, what are your recommendations?
    j
    s
    +4
    • 7
    • 20
  • m

    melatonina

    11/26/2019, 12:05 AM
    Hello. I'm trying to use com.shopify.livedataktx.MutableLiveDataKtx to avoid the invasion of nullables and !! in kotlin code using ViewModel. How do you make a two-way binding with that kind of MutableLiveDataKtx?
    r
    • 2
    • 15
  • a

    Aiden

    11/26/2019, 10:23 AM
    I have a ProductDao interface class which implemented(?) by ProductDatabase. Maybe I should not say implemented(?), because it is not using the
    implements
    word. 1. Why the ProductDatabase can use
    abstract
    to initialize
    interface
    class?
    abstract fun productDao(): ProductDao
    2. What does the line of code means and trying to do?
    @Database(entities = [Product::class], version = 1)
    abstract class ProductDatabase : RoomDatabase() {
        abstract fun productDao(): ProductDao
    }
    
    @Dao
    interface ProductDao {
        @Insert
        fun insert(product: Product)
    
        @Update
        fun update(product: Product)
    
        @Delete
        fun delete(product: Product)
    
        @Query("SELECT * FROM products")
        fun all(): LiveData<Array<Product>>
    
        @Query("SELECT * FROM products WHERE id = :id")
        fun get(id: Int): Product
    }
    b
    a
    • 3
    • 4
  • a

    Ayden

    11/26/2019, 4:36 PM
    If there any difference between
    Java::class.java
    and
    Java::class
    ? Why sometime I need to passing the first option as a parameter but sometime I need to pass the second option?
    l
    c
    • 3
    • 4
  • a

    Arslan Mushtaq

    11/26/2019, 8:03 PM
    Hello everyone, I wanted a solution to a certain problem. I am using a query to get the count of items with Room. I am using a suspend function with return an Int and in my repository class a suspend function which returns an int and when it comes to the view model class I don’t know how to get the return value from the suspend function without using runBlocking. I want to update the fragment when the app starts and before I navigate to the fragment.
    v
    • 2
    • 3
  • r

    rodrigo

    11/26/2019, 8:52 PM
    I am facing a weird issue with Kotlin synthetic on Android, at
    onActivityCreated
    I have a field
    reference_field.addTextChangedListener()
    and then I navigate to a different screen (Fragment), however when I navigate back the listener no longer works and I think it has something to do with how Kotlin Android Extensions use cached views, on the other hand if I replace
    reference_field.addTextChangedListener()
    with
    view?.findViewById<EditText>(R.id.reference_field)?.addTextChangedListener()
    then navigate to a different screen and return to the previous screen the listener does work as intended. Perhaps when the view gets destroyed and recreated Kotlin synthetic is referring to a cached reference which no longer exists 🤔. Has anyone experienced this before?
    a
    s
    • 3
    • 2
  • r

    Rafa

    11/27/2019, 12:42 AM
    I just updated to Kotlin 1.3.60 and when I try and build my project I get
    Unable to load class 'kotlin.coroutines.Continuation'
    on the task
    :app:kaptGenerateStubsDevDebugKotlin
    When I revert back to kotlin 1.3.50, it builds fine and everything works. Is there anything about 1.3.60 that might be causing this to happen?
    d
    h
    +2
    • 5
    • 5
  • g

    gabin

    11/27/2019, 10:07 AM
    Hello guys. Could someone tell how can I update kotlin plugin to 1.3.61 in Android Studio 4.0 Preview ? The message in preferences says “A new version is found but not verified”
    g
    a
    a
    • 4
    • 4
  • g

    Guilherme Krzisch

    11/27/2019, 8:32 PM
    I'm receiving
    java.lang.AbstractMethodError: abstract method "void android.os.Parcelable.writeToParcel(android.os.Parcel, int)"
    when putting the app in background, after saving a parcelable (using
    Parcelize
    ) in
    onSaveInstanceState
    :
    override fun onSaveInstanceState(outState: Bundle) {
        outState.putParcelable("test", Test())
        super.onSaveInstanceState(outState)
    }
    
    @Parcelize
    data class Test(val test: String = "test"): Parcelable
    It does not occur on configuration changes though. I'm using AS 4.0 Canary 4, with kotlin
    1.3.60-eap-25
    . Any idea of what am I doing wrong here?
    d
    • 2
    • 2
  • i

    Ive Vasiljevic

    11/28/2019, 3:38 PM
    Kotlin has a number of Android Extensions and one of them is that by referencing the ID of the view findViewById method is not necessary. And it is actually using cache so when you access that same view it is taken from cache. This works for Activity and Fragment classes, but when referencing a view by its ID from a custom class such as ViewHolder there is no cache and for every view in RecyclerView findViewById is called, so in that case I need to implement LayoutContainer interface on that class. So my question is, is this implementation still necessary in late 2019?
    :yes: 1
    t
    r
    • 3
    • 2
  • v

    voben

    11/28/2019, 5:47 PM
    I’m trying to send data from an android service to an activity. I would usually do this with a broadcast receiver, but I was wondering if this was something I could use a Coroutine channel for and how would that work?
    p
    c
    m
    • 4
    • 5
  • d

    Diego Almeida de Oliveira

    11/28/2019, 9:02 PM
    Hello everyone. I published this article that talks the guide to app architecture provided by Google, and how using it without extra care might lead to ViewModels being leaked. I'd appreciate if you could take some minutes to read it and give me some feedback. Thanks :) https://cheesecakelabs.com/blog/android-architecture-components-viewmodel-leak/?utm_source=linkedin&amp;utm_medium=post&amp;utm_campaign=blogpost-viewmodel
    t
    a
    +2
    • 5
    • 11
  • f

    Freedom

    11/28/2019, 9:23 PM
    Can any one help how can I send a request in parallel using coroutines for example I am sending a list of images to the server in parallel or sequentially
    p
    j
    • 3
    • 6
  • d

    darkmoon_uk

    11/30/2019, 6:53 AM
    ❓ Kotlin Test not integrated with Android Studio - expected? When defining Unit Tests using only
    kotlin.test
    classes; Android Studio doesn't provide the same IDE integration as when using JUnit classes. Specifically: Right-click execution of test classes & individual tests, and capturing the results of the tests in the IDE UI. Is this expected? Seems like a surprising omission.
    t
    • 2
    • 1
  • t

    tjohnn

    11/30/2019, 7:06 AM
    Is view-binding available in studio 4.0 canary? I can't get my gradle to synchronize after adding it.
    v
    • 2
    • 4
  • k

    KV

    12/01/2019, 2:27 PM
    Hi Guys, I am facing an issue while writing the data (Append the data) into raw (demofile.txt) folder. I am able to read the data but the I can’t append the data. My Reading functionality is looking like this from raw folder
    fileContent = readFileFromRawDirectory(R.raw.demoFile) . ---> This is the file inside the /raw folder
    
    private fun readFileFromRawDirectory(resourceId: Int): String {
            val iStream: InputStream = context?.resources.openRawResource(resourceId)
            var byteStream: ByteArrayOutputStream? = null
            try {
                val buffer = ByteArray(iStream.available())
                iStream.read(buffer)
                byteStream = ByteArrayOutputStream()
                byteStream.write(buffer)
                byteStream.close()
                iStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return byteStream.toString()
        }
    Now I want to add the data inside the same demoFile.txt This below code is for writing the string inside the demoFile.txt
    private fun writeDataIntoFile(searchText: String) {
            val file = context?.filesDir?.absolutePath + "/demoFile.txt"
            try {
                val fileout: FileOutputStream? = context?.openFileOutput(file, MODE_PRIVATE)
                val outputWriter = OutputStreamWriter(fileout)
                outputWriter.write(searchText)
                outputWriter.close()
                fileout?.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    :stackoverflow: 5
    r
    • 2
    • 6
  • a

    Arjun Achatz

    12/02/2019, 5:19 AM
    Anyone know how to keep kotlin.ws.kts within an Android project ? I'd like to keep my kotlin script within my android studio project so that others can use it without installing extras. I also don't know how to use dependencies within the kotlin script if it needs to be run alone (for example gson; so potentially question 2) Is anyone familiar with this ?
    s
    • 2
    • 5
  • m

    Matej Drobnič

    12/02/2019, 6:53 AM
    Is there any information out there on how Android plugin version in IntelliJ maps to Android Studio version? For example, what Android Studio version does Android plugin in IntelliJ 2019.3 map to?
    :stackoverflow: 2
    s
    g
    • 3
    • 29
  • m

    Mullisgabriele

    12/02/2019, 9:35 AM
    Anyone know how to create a flavor config using gradle.kts? I've found this medium articled(link below) that does something similar but it isn's in .kts...https://medium.com/stepstone-tech/modularizing-your-flavored-android-project-5db75c59fb0d
    m
    • 2
    • 5
  • j

    Joey

    12/03/2019, 8:35 AM
    Any idea why my app crashes when calling
    fetchHeartbeat()
    in my
    MapsActivity.kt
    t
    p
    r
    • 4
    • 11
  • n

    Nikola Milovic

    12/03/2019, 9:56 AM
    Type inference failed: fun <T : Any!> getSystemService(context: Context, serviceClass: Class<T!>): T?
    cannot be applied to
    (String)
    Type mismatch: inferred type is String but Context was expected
    I just used the code provided here https://developer.android.com/guide/topics/text/copy-paste
    var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    var pasteData: String = ""
    And i get this error
    w
    m
    • 3
    • 7
Powered by Linen
Title
n

Nikola Milovic

12/03/2019, 9:56 AM
Type inference failed: fun <T : Any!> getSystemService(context: Context, serviceClass: Class<T!>): T?
cannot be applied to
(String)
Type mismatch: inferred type is String but Context was expected
I just used the code provided here https://developer.android.com/guide/topics/text/copy-paste
var clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
var pasteData: String = ""
And i get this error
w

wasyl

12/03/2019, 9:59 AM
You’re using
getSystemService
from core-ktx library and it’s a function with reified generic parameter. So you need to instead wrote
getSystemService<ClipboardManager>()
n

Nikola Milovic

12/03/2019, 10:46 AM
@wasyl still not working, this is in my ViewModel, it's troubleing me for a while now. Everyone does it this way but it doesnt work for me
w

wasyl

12/03/2019, 11:11 AM
Oh, in that case you can’t get system service from a class that doesn’t extend a Context
and ViewModel doesn’t
n

Nikola Milovic

12/03/2019, 11:26 AM
Yeah I've done some research now, but I am still confused. I want to keep my logic away from my fragment and in my viewmodel. So i just call
override fun quoteClicked(quote: Quote) {
        viewModel.copyText(quote)
    }
in my fragment, but now I need a way to copy text in the viewmodel. Any pointers/ help/ article would be appreciated. Not sure what to do Thanks by the way @wasyl
m

Mark Murphy

12/03/2019, 12:15 PM
If you are using dependency inversion (Dagger, Koin, etc.), you could inject the
ClipboardManager
so you can supply a mock version in testing. Otherwise, you could have your viewmodel extend
AndroidViewModel
and use the
application
to call
getSystemService()
.
n

Nikola Milovic

12/03/2019, 12:49 PM
Hmm I'll do the DI approach, thanks!
👍 3
View count: 30