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

    user

    07/04/2022, 11:11 AM
    How to adjust toolbar color on BottomSheet expand slide I'm using bottom sheet on my screen. Also here i have appbar which is transparent. When i expand my bottom sheet it's expand to appbar height. But the problem is - my appbar still transparent. I want to animate of fading this color into black when bottom sheet expanding to fullscreen and make it transparent again when bottom sheet is half expanded. I have callbacks on slide of bottom sheet: private fun addBottomSheetCallback(bottomSheetBehavior: BottomSheetBehavior) {...
  • u

    user

    07/04/2022, 11:11 AM
    How to set margin in SnackBar I'm trying to add margins at bottom, left and right to my SnackBar but I'm not able to get it. That's what I tried: var snackBar = Snackbar.make(binding.root,msg,Snackbar.LENGHT_LONG) var snackbarLayout = snackBar.view. as Snackbar.SnackbarLayout var layoutParams = snackbarLayout.layoutParams as CoordinatorLayout.LayoutParams layoutParams.setMargins(32,0,32,32) snackbarLayout.layoutParams = layoutParams snackBar.show() I get an error in snackbarLayout.layoutParams and its this:...
  • u

    user

    07/04/2022, 11:51 AM
    How to let kotlin library support java project friendly I create an kotlin library and published into maven central. However, if this library is used by pure java project, user must add the dependency “kotlin-stdlib” explicitly. It looks like that the “koitlin-stdlib” is automatically excluded from grade/maven dependency tree because it is treated as provided dependency. How to resolve this problem?
  • u

    user

    07/04/2022, 11:51 AM
    Spring native TypeHint name expect and element expected error So i am trying to setup PostgreSqlDilect by following this StackOverflow ans. and when I compile the project.I get the following error
    Task :kaptGenerateStubsKotlin FAILED e: /home/boris/IdeaProjects/kastbin/src/main/kotlin/com/kastbin/KastbinApplication.kt: (8, 67): Name expected e: /home/boris/IdeaProjects/kastbin/src/main/kotlin/com/kastbin/KastbinApplication.kt:...
  • u

    user

    07/04/2022, 12:11 PM
    Kotlin - Ktor Optional API resource field handling When implementing a REST API with Ktor (and Kotlin), it supports the optional field handling of Kotlin. Which works for POST and GET, but what about UPDATE? For example, you have the following resource: @Serializable data class MyAddress( var line1: String? = null, var line2: String? = null, var city: String? = null, var postal_code: String? = null, var state: String? = null, var country: String? = null ) So all MyAddress fields are optional (with a default value)....
  • u

    user

    07/04/2022, 12:31 PM
    Matched object type miss when expression case. Kotlin It just blew my mind. So maybe someone was faced with such a problem. I try to use a new approach for Retrofit with statements. The problem is that even with a matched instance of the result else block applies. How can it be? override fun invoke(result: GraphCallResult) { when(result) { is GraphCallResult.Success -> { collections.postValue(Converter.convertCollections(result.response.data?.collections)) loading.postValue(false)...
  • u

    user

    07/04/2022, 12:31 PM
    UninitializedPropertyAccessException in Android Studio with viewModel I'm New to Kotlin and Android Studio and trying to implement Room database with ViewModel now, but I face the problem "kotlin.UninitializedPropertyAccessException: lateinit property habitViewModel has not been initialized" I think that this is due to the early initialization of View Model, but I can't find the way to fix it. This is my code below. Activity OnCreate Code class HabitActivity : AppCompatActivity() { lateinit var binding : ActivityHabitBinding lateinit var habitViewModel...
  • u

    user

    07/04/2022, 12:31 PM
    Glide is not loading images from firebase child key folder ##Kotlin## Ive Started studying kotlin and im trying to upload and retrieve details(to recycler view) from firebase realtime database. while uploading an entry(both text and imageUrl) into realtime database ,text entries are made but getting cleared at once image(single image or multiple image) gets uploaded. Only imageUrl alone is getting stored. For that i used push() method to make entry for imageUrl and its working fine. Now the problem is retrieving the imageUrl from child key folder. when i tried...
  • u

    user

    07/04/2022, 1:11 PM
    Periodically refresh Kotlin flow (polling) How shoud I peridically "refresh" kotlin flow, to get fresh data. I have list of book id's stored in room database. From network api I get the actual books using the stored ids. My goal is to listen database changes and map the book ids to actual books. That works fine. The problem is, how shoud I re-fetch periodically book data from network api but still keep listening the database all the time? So changes in book ids in database shoud allways trigger network api call (booksApi.get()). fun...
  • u

    user

    07/04/2022, 1:31 PM
    How to implement package manager in fragment? I try to implement package manager in Fragment, but it seems that in fragment we can't implement package manager. Here the code I use: private fun takePhoto() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) intent.resolveActivity(packageManager) createTempFile(application).also { val photoURI: Uri = FileProvider.getUriForFile( this@CreateStoryActivity, "com.dicoding.bpaai.submission", it )...
  • u

    user

    07/04/2022, 2:11 PM
    Jetpack Compose set image height before loading remote image I have a list of dynamically sized images. I already know the size of the images in pixels. I would like to place a placeholder of the same remote image dimension before the image is loaded just so that while scrolling in the LazyColumn the list doesn't jump up and down Given the following code, which uses Coil: @Composable fun CloudImage( url: String, modifier: Modifier = Modifier, imageHeight: Int // I also got the image width... but I am using ContentScale = Fit ) { AsyncImage(...
  • u

    user

    07/04/2022, 2:51 PM
    React native android emulator Task :app:packageDebug FAILED error I got this error while react-native run-android. I tried ./gradlew clean ./gradlew -stop and wipe data, remove build folder, .gradle folder etc... But can't solve the problem. Here is the error code I got. Does anyone has an idea to solve that problem? $ react-native run-android warn Package @svgr/webpack has been ignored because it contains invalid configuration. Reason: Package subpath './package.json' is not defined by "exports" in (...)/node_modules/@svgr/webpack/package.json info Running...
  • u

    user

    07/04/2022, 2:51 PM
    lateinit property mClickListener has not been initialized Adapter kotlin i make adaper onclick listener but somehow theres error message lateinit property mClickListener has not been initialized Adapter kotlin variable on click lateinit var mClickListener: ItemClickListener base view holder inner class AdapterListProjectVH2(itemView: View) : BaseViewHolder(itemView), View.OnClickListener { private val cvItemViewVisualInsp: CardView = itemView.findViewById(R.id.cv_itemview_visual_insp) private val imgMarkOnMap: ImageView =...
  • u

    user

    07/04/2022, 2:51 PM
    kotlin.reflect.jvm.internal.KotlinReflectionInternalError when minifyEnabled I get a problem. when my app minifyenabled is true , it crashed ! and the error is following: kotlin.reflect.jvm.internal.KotlinReflectionInternalError: This callable does not support a default call: public constructor LoginResultBean I think there must be some relationships with moshi and R8. I need help...
  • u

    user

    07/04/2022, 2:51 PM
    Kotlin: ListVew inside a fragment i am trying to create a very simple listview inside a fragment but there is something that i am doing wrong and the list view doesnt show on the screen. this is my fragmentWifi.kt: import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button import android.widget.ListView // TODO: Rename parameter arguments, choose names that match // the...
  • u

    user

    07/04/2022, 3:11 PM
    Android toast displaying incorrect String value When setting a switch as off the user should receive a toast saying "alarm set for 00.40" for example, but for some reason the "alarm set for" has been swapped out for a string of numbers as below.

    https://i.stack.imgur.com/sMyLs.png▾

    The code: override fun setSwitchOn(alarm: Alarm) { val toastTime = formatTime(alarm) val alarmManager = AlarmManager( alarm.id, alarm.hour,...
  • u

    user

    07/04/2022, 3:31 PM
    Kotlin VideoView path with a changing resource name I have a group of mp4 files (v1.mp4, v2mp4,...) inside the raw folder. I need to read them randomly after a button is clicked. I get the message "not possible to play this video". If I point to a specific file in the setVideoPath, ("android.resource://" + packageName + "/" + R.raw.v2) the video is played, but do not change when the button is hit. My code is the following: fun onClick(view: View) { // Change the word randomly randOne = ThreadLocalRandom.current().nextInt(1,...
  • u

    user

    07/04/2022, 3:31 PM
    Custom Options Menu item does not trigger `onOptionsItemSelected` when clicked In my top AppBar options menu I needed an custom menu item, so I defined it like so in my Fragment: override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menu.add(Menu.NONE, 0, Menu.NONE, R.string.share) .setActionView(R.layout.menu_item_share_button) .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) menu.add(Menu.NONE, 1, Menu.NONE, R.string.settings) .setIcon(R.drawable.bootstrap_icon_gear_fill)...
  • u

    user

    07/04/2022, 3:51 PM
    popupTo property disturbs the exitanim opteration While Logging out from HomeFragment to LoginFragment everything works fine except the app:exitAnim="@anim/slide_out_right" which doesn't take effect but behaves according to the previous operation while moving from LoginFragment to HomeFragment app:exitAnim="@anim/slide_out_left" Problem starts when I use the property app:popUpTo="". I just want to exitAnim to right but it moves to the left, don't know why. Thanks for your time and help Note: while moving back from DetailFragment to...
  • u

    user

    07/04/2022, 3:51 PM
    Consuming a Kotlin Function with an Argument in a Java file using the correct syntax I have a variable called onItemSelected in a Kotlin file var onItemSelected: ((String) -> Void)? = null In a Java file I am trying to set that variable, but am unable to figure out the correct syntax. The lambda expression keeps wanting to return a Void, however, when I return a void, then it doesn't compile. binding.myCustomView.getOnItemSelected() = (item, Void) -> { //What should happen here? Log.i("Test", item); return; }; I have tried various syntax,...
  • u

    user

    07/04/2022, 3:51 PM
    Livedata room : dao query returns null in my MVVM project I am using live data queries to DAO to update the live data of the list of data in my ViewModel and then bind this livedata to adapter binded to recycler view in the fragment, it works correct except for the case when there are 2 queries in a row to room database , so it returns null pointer and doesn't properly update UI. Part of the fragment code: @AndroidEntryPoint class HomeFragment : Fragment(), NoteCardAdapter.NoteTouchListener, SearchView.OnQueryTextListener{...
  • u

    user

    07/04/2022, 4:11 PM
    Hibernate pagination not working when using native queries (Named query exists but its result type is not compatible) I have a two named native queries in my orm.xml, one for retrieving the data, and one for doing the count for my pagination: select count(*) from from person select first_name, last_name from person To load this data, I have a Spring Data Repository, which loads a projection of the data (my actual code is more complex than the provided example): @Query(nativeQuery = true) fun findPeople(pageable: Pageable): Page Now, when I execute the above code,...
  • u

    user

    07/04/2022, 4:31 PM
    Is it possible to set realtime database value using setValue() function in the adapter? I am trying to set the value of the realtime database using setValue() function. I don't know it works or not, but I have seen many using setValue() function in the model but they never used it. But I am trying to implement in my code. here is my adapter code:- class PostsAdapter( private var mContext: Context, private var mPosts: List, private var isFragmnet: Boolean = false ) : RecyclerView.Adapter() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):...
  • u

    user

    07/04/2022, 4:31 PM
    Safeargs library don't create SpecifyAmountFragmentDirections After adding the argument, the library doesn't create the Direction class for me to be able to pass arguments This is my code: nav_graph.xml build.gradle: dependencies { classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5" } plugins { id 'androidx.navigation.safeargs.kotlin' } I'm currently working with Android Studio 4.1.2. I tried to invalidate the cache, clean the project and rebuild it but it didn't work. Looking through the old answers I...
  • u

    user

    07/04/2022, 4:31 PM
    Kotlin - mutableList always returns empty list I'm using a range with an inline transform so that I can have a list of values and that I want to send it to a method in forEach. But, somehow I see that is not happening. This is the example code I'm using var valuesList: List = mutableListOf() (1..5).map { valuesList.plus(Test(, Instant.now()) // Have a condition to check the value and using the value in next statement valuesList.plus(Test(, Instant.now()) }.forEach { } Somehow I always see valuesList as empty list. Can anyone...
  • u

    user

    07/04/2022, 5:11 PM
    Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0 I have been working on this project and everything seem perfect until about a week ago, I tried to launch the project on an emulator and ran into the error below. $ yarn react-native run-android yarn run v1.22.15 $ C:\Users\Chifes\Desktop\apps\RoGoods\node_modules\.bin\react-native run-android info Running jetifier to migrate libraries to AndroidX. You can disable it using "--no-jetifier" flag. Jetifier found 1519 file(s) to forward-jetify. Using 4 workers... info Starting JS server... info...
  • u

    user

    07/04/2022, 5:11 PM
    Play random sound from RAW, on Button click I am relatively new to Kotlin. I want to play a random sound from my RAW folder, every time I click the play button. There are about 13 sound file in my RAW folder. mMediaPlayer = MediaPlayer.create(this, R.raw.d) mMediaPlayer?.start()
  • u

    user

    07/04/2022, 5:31 PM
    Kotlin, how can I read a dynamic website as text? As titled, I'm trying to read the content of sites like this one, which appears to be javascript based. I tried using plain jdk lib, then jsoup and then htmlunit, but I couldn't get anything useful out of it (I see just the source code or just the title or...
  • u

    user

    07/04/2022, 6:11 PM
    Attempt to invoke virtual method 'void androidx.lifecycle.MutableLiveData.setValue(java.lang.Object)' on a null object reference (Android Kotlin) Sorry for the long title, however, I am unsure where this error is at in my code, however, I do suspect the error lies in the implementation of the liveData and Observation. The app which I am working on is an Unscrambler word app where users have to unscramble the letters displayed on the fragment. My code so far consists of 2 Kotlin classes listed below, a fragment and a ViewModel class. I have currently assigned the variable _currentScrambledWord as a MutableLiveData() and utilised the...
  • u

    user

    07/04/2022, 6:31 PM
    Kotlin For loop, confused Does anyone explain how it works? X and Y answer explain, please.Answer: 81 and 23
    fun main(args: Array) {
        var x =0
        var y =20
        for (outer in 1..3) {
         for (inner in 4 downTo 2) {
            x += 6
            y++
            x += 3
            }
            y -= 2
        }
        println("$x $y")
    }
Powered by Linen
Title
u

user

07/04/2022, 6:31 PM
Kotlin For loop, confused Does anyone explain how it works? X and Y answer explain, please.Answer: 81 and 23
fun main(args: Array) {
    var x =0
    var y =20
    for (outer in 1..3) {
     for (inner in 4 downTo 2) {
        x += 6
        y++
        x += 3
        }
        y -= 2
    }
    println("$x $y")
}
View count: 15