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

    user

    06/20/2022, 1:41 AM
    How to use flow with workManger I need got the data form background , this job will accompany the hole app life cycle . I try to use WorkManager to instead of Service. Read the android develop guide , I guess should use CoroutineWorker , And use Data api to return a Flow. It's diffcuclt to me , I have no idea to write the code ~
  • u

    user

    06/20/2022, 3:41 AM
    FileNotFound Exception when saving an image to sub directory in external storage private fun takeScreenshot() { val now = Date() val formattedTimestamp = DateFormat.format("yyyy-MM-dd_hh🇲🇲ss", now) try { //val mPath : String = Environment.getExternalStorageDirectory().toString().toString().toString() + "/" + formattedTimestamp + ".jpg" // image naming and path to include sd card appending name you choose for file val mPath: String = Environment.getExternalStorageDirectory().toString().toString() + "/mobile/" +...
  • u

    user

    06/20/2022, 4:01 AM
    Unresolved reference: getInstance [kotlin android studio] getInstance of kotlin is showing error as "Unresolved reference: getInstance" in MainActivity.kt. I am trying to implement singleton but getInstance is not working. Maybe something wrong in this line "MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)" in MainActivity.kt. MainActivity.kt package com.example.newstube import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager...
  • u

    user

    06/20/2022, 4:21 AM
    Set type of a variable dynamically in kotlin I'm trying to make a generic model in which some fields are fixed and only one field changes, so the model is class APIResponse( var msg: String? = null, var code: String? = null, var data: Any? = null // dynamic field ) I want to set data variable of this APIResponse class to other different types on the go with the help of a function: fun generateApiResponseAdapter(type: Any): APIResponse { return APIResponse(null, null, type) } so for example if I have a model as: class...
  • u

    user

    06/20/2022, 4:41 AM
    Sort a file with a specific line pattern in Python Given a file with the following content: enum class Fruits(id: String) { BANANA(id = "banana"), LEMON(id = "lemon"), DRAGON_FRUIT(id = "dragonFruit"), APPLE(id = "apple"); } I want to sort this file given the pattern "id = ", and then replace these lines with the new sorted lines. I wrote a piece of code in python that sorts the whole file, but I'm struggling with regex to read/find the pattern so I can sort it. My python script: import re fruitsFile =...
  • u

    user

    06/20/2022, 5:01 AM
    Kotlin firebase executed with addOnSuccessListener even if fails I have this piece of code and it is executed with .continueWith and addOnSuccessListener even if failed.I try with continueWithTask but i dont understand very well Tasks API. Please help me to understand how to do this. db.collection(customGameName).document().get().continueWith { if (!gameslist.contains(customGameName)) { gameslist.add(customGameName) SavedPreference.setGamesList(this, gameslist) adapter.notifyDataSetChanged() }else{...
  • u

    user

    06/20/2022, 5:01 AM
    Start time gets updated every-time app is launch Requirement - App needs to be logged out everyday at specific time irrespective of whether app is in background or foregound. Solution - Run a snippet every day to logout user from the app. WorkManager has periodic work with initial delay which can be set at specific time and runs periodically. Issue - schedule_requested_at is updated every time app is launched available under WorkSpec table. Though initial_delay remains the same. Used App Inspection to view Database. Same can be visible...
  • u

    user

    06/20/2022, 7:41 AM
    Kotlin Google MLKIT Face Detection , Face Circular Motion Enrollment I was building a face enrollment feature using google's mlkit, I am trying to capture circular motion enrollment like that of ios as shown below

    https://i.stack.imgur.com/D82P8.pngâ–¾

    I was able to achieve everything but i am only stuck in the circular motion part, what I have used is the following private fun Direction(): Boolean { if (angley in 20f..25f && anglez in 2.0f..6.0f) { return true } return false }...
  • u

    user

    06/20/2022, 8:21 AM
    How to get Twitter data without using APİ in Kotlin? I want to build an Android app using Twitter data such as followers and likes of an account. First i tried to use official Twitter api but because of the limitations (set by Twitter) it was not good for me to use Twitter api in an Android app. I understand that Twitter needs to have some limitations to keep their database not busy. Than, i tried to use jsoup library to scrape data from Twitter. I was not able to get any data (i am not sure if i used jsoup correctly) Is there any way i could...
  • u

    user

    06/20/2022, 8:21 AM
    Firestore keeps on sorting on two fields, but I only want to sort on one field I have a collection "records". A record is just a time set by a user when they clear a puzzle. Record has the fields: uid (id of the user who set the record) time (time taken to finish) type (either "memory" or "word" which are the two types of puzzles that a user can clear) I just want to sort the records by time to show a leaderboards screen. db.collection("records") .whereEqualTo("type", "memory") .orderBy("time", Query.Direction.ASCENDING) For some reason, the results are always...
  • u

    user

    06/20/2022, 8:21 AM
    Register issue with login system in Kotlin On Login page and when pressing register, it takes you to register, but when clicking on register button on register page, it adds user to database regardless if info is provided or not and then takes you back to login page. I want the validation to happen before the execution. Currently it does validate, but executes regardless. Please advise. import android.content.ContentValues import android.content.Intent import android.os.Bundle import android.text.Editable import...
  • u

    user

    06/20/2022, 8:41 AM
    Find max characters can fit in one line of Android Jetpack compose Text I want to find the total number of characters that can fit in one line of a current Jetpack compose Text Any field where I can get this information. Thanks
  • u

    user

    06/20/2022, 9:41 AM
    Kafka TestContainers fails to connect I have a very simple TestContainers Kafka + Kotlin test that fails because my test code cannot connect to the Kafka instance. My Class def looks like this: @Testcontainers class SimpleKafkaTest { @Container val kafkaContainer = KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:6.2.1")).withEmbeddedZookeeper().waitingFor( Wait.forListeningPort()) Now my test beings as follows: @Test internal fun `test kafka`() { kafkaContainer.start()...
  • u

    user

    06/20/2022, 9:41 AM
    How do I write Nested Generics in Kotlin's Sealed Classes I'm trying to come up with a data model that allows me to do the following: Define a type of Task and change its Status This Status can be either InProgress or Completed In the case of a completed Status, I want to be able to add data, that is specific to the Task that was completed. Initially, I came up with this data model: sealed class Task { abstract val status: TaskStatus data class A( val data: String, override val status: TaskStatus, ) : Task()...
  • u

    user

    06/20/2022, 10:01 AM
    Getting build issue while building kotlin code. "Unresolved reference: datetime in kotlin " The Complete error is Execution failed for task ':compileKotlinJs'. Compilation error. See log for more details Unresolved reference: datetime this issue is coming when I do "import kotlinx.datetime.Clock" and i have implemented implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.1.1"). Can someone help ?
  • u

    user

    06/20/2022, 10:01 AM
    How to initiate array items using for loop in Kotlin Python allows programmers to perform such an operation: mylist = [1, 2] items = [value * 2 for value in namelist] How can I achieve the same using Kotlin, I want to pass values multiplied by 2 from mylist into the array below: val mylist = mutableListOf(1, 2) val (first, second) = arrayOf( ) Kotlin allows us to to declare and initiate variables with one liners as below val (first, second) = arrayOf(1, 2) that way you can call first or second as a variable. Am trying to make the equal part...
  • u

    user

    06/20/2022, 10:21 AM
    Android DiffUtil Doesn't Notify Properly I was following along the Android Room With a View tutorial. The tutorial makes use of DiffUtil to compute changes in the list and update the RecyclerView accordingly. However, when removing or adding items to the RecyclerView, DiffUtil always causes the entire RecyclerView to reload, instead of calling the correct notifyItemRemoved or notifyItemInserted. My Adapter: class...
  • u

    user

    06/20/2022, 10:21 AM
    How to call a companion object list in the activity using its name? I am trying to call a companion object list(present in other file) using the name of the list that is present in the spinner. here is spinner code:- private fun selectcourseCheckboxes() { val courseList: Array = resources.getStringArray(R.array.courses) val courseListAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, courseList) courses_spinner_quiz_location.adapter = courseListAdapter courses_spinner_quiz_location.onItemSelectedListener =...
  • u

    user

    06/20/2022, 10:21 AM
    RxJava show Loading when http request takes more than given amount of time Problem: Recently a design team on a project I'm working on came up with an idea to show loading states only when http request takes more than two seconds to complete. I wanted to go for a reusable piece of code and I created an extension. My approach: Let's say we have 2 seconds delay time after which loading should appear on the screen. In case I get the successful response quicker than 2 seconds, takeUntil completes when condition is satisfied. Loading is not emitted. In case successful...
  • u

    user

    06/20/2022, 10:41 AM
    User Defined Base URL With Retrofit The application I work on must use a different Base URL for every user. Basically the user has his own server, and in the application he must specify the IP Address for his server in a Text Field so the application can start doing HTTP Requests to that server. When I create the Retrofit instance it requires a Base URL, but there is now way I can access it from the UI, since the user has to enter the base URL manually from a Text Field. As a workaround I just pass Google as the Base URL when I...
  • u

    user

    06/20/2022, 10:41 AM
    Null pointer Exception in Android when using Glide Here is the logcat output 2022-06-20 13:19:27.605 20830-20830/com.example.moveapplication E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.moveapplication, PID: 20830 java.lang.NullPointerException: Argument must not be null at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:29) at com.bumptech.glide.util.Preconditions.checkNotNull(Preconditions.java:23) at com.bumptech.glide.RequestBuilder.into(RequestBuilder.java:768) at...
  • u

    user

    06/20/2022, 11:01 AM
    Sending a form urlencoded POST request with Ktor Client? I am wanting to utilize the Ktor client library to interact with a Web API, specifically to authenticate via OAuth, and I'm running into trouble attempting to send a form urlencoded POST request properly. It would appear the actual body is not being sent for some reason. I've tried looking at similar questions on SO, such as <a href="https://stackoverflow.com/questions/53595544/send-application-x-www-form-urlencoded-in-ktor">this...
  • u

    user

    06/20/2022, 11:01 AM
    Is sequence referred to internal DSL in Kotlin? In book 'Kotlin in Action', it says Kotlin DSL structure is most commonly created through chained method calls. Also, a typical library consists of many methods and no context is maintained btw one call and the next. I'm confused of which side sequence is close to. Before I read this, I've thought sequence is just API of library, but it really fits with feature of DSL.
  • u

    user

    06/20/2022, 11:21 AM
    convert kotlin/java set to scala immutable Id like to convert an existing kotlin/java set, to scala immutable set, using kotlin/java code. scala.collection.JavaConversions.asScalaSet only gives me the mutable set. Must do it that way, because I am inheriting from a scala class on another repo, and would not like to insert scala packages and plugins to my project.
  • u

    user

    06/20/2022, 11:41 AM
    Android, how to implement an amoled theme over night mode I am making a simple app in kotlin and would like to add an additional option for night mode like this

    example from Material Files appâ–¾

    I was thinking of adding a style and applying it programmatically, But I don't know how to do it properly. Here's my code: MainActivity override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false)...
  • u

    user

    06/20/2022, 12:01 PM
    Navigation action/destination ,action_OTPFragment_to_confirmOTPFragment cannot be found from the current destination Destination

    https://i.stack.imgur.com/PMbAU.pngâ–¾

    This is the error in log cat

    https://i.stack.imgur.com/COgxt.pngâ–¾

    https://i.stack.imgur.com/OelNn.pngâ–¾

    I got error when click on submit button while navigating from from OTP to confirmOTP with Arguments
  • u

    user

    06/20/2022, 12:01 PM
    Android camera intent not working in version 12 The camera does not open in android version 12, what can I do for it?
  • u

    user

    06/20/2022, 12:21 PM
    What am I missing while fetching the data for caching purpose using Retrofit that it gives me 504 Unsatisfiable Request I am trying to implement cache request using Retrofit by fetching random joke from an API and displaying it in Textview but when I click the button it keeps giving me '504 Unsatisfiable Request(only-if-cached). Base url of my API is following one:- api and following are the classes. APIService.java import com.example.cachingretrofit.JokeResponse import retrofit2.http.GET import io.reactivex.rxjava3.core.Observable...
  • u

    user

    06/20/2022, 12:21 PM
    How to transform the Array of object to an object in Kotlin I have a list of object Ftemp(Wert_1_id='I130320', Wert_2_id='I130278', Wert_3_id='I130115') Ftemp(Wert_1_id='I130320', Wert_2_id='I130278', Wert_3_id='I130108') Ftemp(Wert_1_id='I130320', Wert_2_id='I130278', Wert_3_id='I130110') Ftemp(Wert_1_id='I130320', Wert_2_id='I130106', Wert_3_id='I130271') and want to transform the list to an object. Like "cat": [ { "id_": "I130320", "children": [ { "id_": "I130278", "children": [ {...
  • u

    user

    06/20/2022, 12:21 PM
    What causes java.lang.IllegalStateException: Failed to load ApplicationContext error? I am new to spring boot, so I don't understand what caused the error mentioned above here since everything gives no warnings and is imported from official libraries import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager import javax.sql.DataSource @DataJpaTest...
Powered by Linen
Title
u

user

06/20/2022, 12:21 PM
What causes java.lang.IllegalStateException: Failed to load ApplicationContext error? I am new to spring boot, so I don't understand what caused the error mentioned above here since everything gives no warnings and is imported from official libraries import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager import javax.sql.DataSource @DataJpaTest...
View count: 7