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

    Colin Gray

    07/13/2021, 2:23 PM
    Is anyone here using SQLDelight w/ a version of sqlite that supports FTS5?
    :not-kotlin: 3
    z
    • 2
    • 1
  • n

    Nikita Khlebushkin

    07/13/2021, 11:29 PM
    Hello! I have a problem with Paging v3 library on Android, here's what happens: When the app is opened, the list is shown correctly and everything is great, but if I call
    invalidate()
    method of PagingSource, then it starts spamming
    load
    method of PagingSource (and doesn't even wait until the job is finished, cancels it and starts anew). This is the stacktrace:
    2021-07-14 02:23:46.189 15215-15254/com.xlebnick.kitties.debug D/OkHttp: --> GET <https://myapi.com/v1/images/search?page=0&limit=24&order=ASC>
    2021-07-14 02:23:46.189 15215-15254/com.xlebnick.kitties.debug D/OkHttp: x-api-key: 9b7e282d-2a67-4c7b-a9fd-3f3e4056e949
    2021-07-14 02:23:46.189 15215-15254/com.xlebnick.kitties.debug D/OkHttp: --> END GET
    2021-07-14 02:23:46.189 15215-15254/com.xlebnick.kitties.debug D/OkHttp: <-- HTTP FAILED: java.io.IOException: Canceled
    2021-07-14 02:23:46.189 15215-15215/com.xlebnick.kitties.debug W/System.err: kotlinx.coroutines.JobCancellationException: StandaloneCoroutine was cancelled; job=StandaloneCoroutine{Cancelling}@6c3004
    And this is my implementation:
    class KittiesPagingSource(
        private val repository: Repository,
        var breedFilter: Breed? = null,
        var likedKitties: List<Like> = listOf()
    ) : PagingSource<Int, Kitty>() {
    
    
        override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Kitty> {
            return try {
                // Start refresh at page 1 if undefined.
                val nextPage = params.key ?: 1
    
                val filters = if (breedFilter != null) listOf(breedFilter!!) else null
                var kitties: List<KittyRemoteModel> = listOf()
                try {
                    kitties = repository.fetchKitties(nextPage, KITTIES_PAGE_SIZE, filters)
                } catch (e: Throwable) {
                    e.printStackTrace()
                }
    
                val newKitties = kitties.map { kitty ->
                    kitty.asKitty(likedKitties.any { it.imageId == kitty.id })
                }
    
                LoadResult.Page(
                    data = newKitties,
                    prevKey = if (nextPage == 1) null else nextPage - 1,
                    nextKey = if (newKitties.isEmpty()) null else nextPage + 1
                )
            } catch (e: Exception) {
                LoadResult.Error(e)
            }
        }
    
        override fun getRefreshKey(state: PagingState<Int, Kitty>): Int? {
            return state.anchorPosition?.let {
                if (it < state.config.initialLoadSize) {
                    // if anchor position is less than initial loading count then download from the beginning
                    0
                } else {
                    // otherwise load a page around anchorPosition using initialLoadSize
                    (it - state.config.initialLoadSize / 2).coerceAtLeast(0)
                }
            }
        }
    }
    private val kittiesPagingFactory = InvalidatingPagingSourceFactory {
            KittiesPagingSource(repository, breedFilter, likedKitties.value ?: listOf())
        }
        private val kittiesPager =
            Pager(PagingConfig(pageSize = 6), pagingSourceFactory = kittiesPagingFactory)
        val kitties: Flow<PagingData<Kitty>> = kittiesPager
            .flow
            .cachedIn(viewModelScope)
    What am I doing wrong?
    d
    e
    d
    • 4
    • 23
  • s

    San

    07/14/2021, 12:46 AM
    Guys gonna switch my full java project into kotlin, wish me good luck!
    🤞 11
    👍 1
    g
    a
    • 3
    • 4
  • a

    ARCHIT JAIN

    07/14/2021, 5:01 AM
    Hello guys!! I am new to android development and recently I have installed the android studio. But there is a error popping up again and again code navigator plugin is incompatible. I have tried to downloaded and installed it manually but still it is not working. Can someone please help?
    :not-kotlin: 5
    👀 1
    g
    • 2
    • 3
  • h

    Hovhannes

    07/14/2021, 6:47 AM
    Hello, I want get the objects from users array from API using Moshi , but I get non understandable error  'Inferred type is UserResponse but User was expected' in  setupObserver(). What mistake did I make? Thanks in advance.
    {
      "users": [
        {
          "id": "1",
          "name": "Bill Roy",
        },
         {
          "id": "2",
          "name": "Ben Bush",
        },
        {
          "id": "3",
          "name": "Dan Fox",
        },
      ]
    }
    User.kt
    data class User(
        @Json(name = "id")
        val id: Int = 0,
        @Json(name = "name")
        val name: String = ""
    )
    data class UserResponse(
        @Json(name = "users")
        val userList: List<User>
    )
    MainViewModel.kt
    class MainViewModel(
        private val mainRepository: MainRepository,
        private val networkHelper: NetworkHelper
    ) : ViewModel() {
    
        private val _users = MutableLiveData<Resource<UserResponse>>()
        val users: LiveData<Resource<UserResponse>>
            get() = _users
    
        init {
            fetchUsers()
        }
    
        private fun fetchUsers() {
            viewModelScope.launch {
                _users.postValue(Resource.loading(null))
                if (networkHelper.isNetworkConnected()) {
                    mainRepository.getUsers().let {
                        if (it.isSuccessful) {
                            _users.postValue(Resource.success(it.body()))
    
                        } else _users.postValue(Resource.error(it.errorBody().toString(), null))
                    }
                } else _users.postValue(Resource.error("No internet connection", null))
            }
        }
    }
     MainAdapter.kt
    class MainAdapter(
        private val users: ArrayList<User>
    ) : RecyclerView.Adapter<MainAdapter.DataViewHolder>() {
    
        class DataViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            fun bind(user: User) {
                itemView.textViewUserName.text = user.name
            }
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
            DataViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.item_layout, parent,
                    false
                )
            )
    
        override fun getItemCount(): Int = users.size
    
        override fun onBindViewHolder(holder: DataViewHolder, position: Int) =
            holder.bind(users[position])
    
        fun addData(list: User) {
            users.addAll(listOf(list))
        }
    }
    MainActivity.kt
    private fun setupObserver() {
        mainViewModel.users.observe(this, Observer {
            when (it.status) {
                Status.SUCCESS -> {
                    progressBar.visibility = View.GONE
                    it.data?.let { users -> renderList(users) }          
                    recyclerView.visibility = View.VISIBLE
                }........
    }
    
     private fun renderList(users: User) {
            adapter.addData(users)                             
            adapter.notifyDataSetChanged()
        }
    :not-kotlin: 1
    l
    • 2
    • 11
  • c

    Colton Idle

    07/15/2021, 12:17 AM
    Compose question but android ish specific so I'm going to ask here first. I have an app with all fragments. I currently check in every fragment if my user is logged out. I follow Ian Lakes video on navigation and everything works really well. I'm moving fully to compose now, no fragments and so now I'm curious how I would do the same check. Overall just curious if someone has docs on how to tackle this use case in pure compose. Basically is there something like this

    https://youtu.be/09qjn706ITA▾

    4:48 but for compose?
    i
    • 2
    • 6
  • r

    Rony Krell

    07/15/2021, 1:37 AM
    Hi there. I have a question about the 1.5.0 release. There's a part of my Kotlin Android app that works fine with 1.4.32 but doesn't work with 1.5.0, 1.5.10, or 1.5.20. It's when a WebView is destroyed. I first remove it from the parent container in the UI and then call destroy on the object itself. In the old version of Kotlin, it works well, but in the newer versions, the variable gets set to
    null
    after the WebView is detached from the parent container. Destroying it later on results in a
    NPE
    . Posted about it here. Have really no idea what it could be after perusing the release notes. Would appreciate any help
    e
    • 2
    • 6
  • l

    Lawrence Shen

    07/15/2021, 7:13 AM
    Has anyone encountered kotlin synthetic doesn't generate _findCachedViewById function after update to version 1.5.x? I have submitted a bug here: https://youtrack.jetbrains.com/issue/KT-47733
    ➕ 1
    z
    • 2
    • 1
  • n

    Noushad Chullian

    07/15/2021, 7:27 AM
    Hi Everyone, Have a doubt, but it is not related to kotlin, but generally any android app I was reading some codes from github, and I found that each use case is written in a different class/File, I dont understand Why people are doing that, since i can write those as functions inside my repository class. Is that a good aproach to abstracting out the use cases seperately??
    ➕ 1
    :not-kotlin: 2
    s
    m
    • 3
    • 3
  • s

    Saidiali

    07/15/2021, 10:00 AM
    Hello, I am having an issue with my application. Its a video call app using peerJs and the webview layout. The app installs but does not start immediately as the normal way. And when I click on the icon, it says app not found. What could be wrong. Here is my manifest file: Any assistance is much appreciated, thank you.
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="<http://schemas.android.com/apk/res/android>"
        xmlns:tools="<http://schemas.android.com/tools>"
        package="com.devhub.meet">
    
        <uses-permission android:name="android.permission.INTERNET"/>
        <uses-permission android:name="android.permission.CAMERA"/>
        <uses-permission android:name="android.permission.RECORD_AUDIO"/>
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:usesCleartextTraffic="true"
            android:theme="@style/Theme.Meet">
            <activity
                android:name=".CallActivity"
                android:exported="false" />
            <activity android:name=".MainActivity"
                android:exported="false">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    :stackoverflow: 2
    u
    c
    • 3
    • 3
  • a

    Anamika Trivedi

    07/15/2021, 1:59 PM
    Hi All! Is there any third party library that I can use for SVG support, Zoom, touch events and has pins support as well? Basically, we are trying to add floor plans in SVG format on the screen and then user can add/change/save pin for any location on the floors.
    :not-kotlin: 4
    k
    • 2
    • 3
  • a

    Anton Afanasev

    07/15/2021, 4:15 PM
    I am trying to read image from asset folder. Android studio gives me a warning saying: "Warning:() Inappropriate blocking method call" even though I call
    open
    from IO Dispatcher. My code:
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
        context.assets.open(FILE_NAME).run {
            this.readBytes().also { file = it }
            this.close()
        }
    }
    Any ideas, folks?
    a
    r
    • 3
    • 4
  • l

    lawlorslaw

    07/15/2021, 6:00 PM
    I know there are a lot of 3rd party libraries on android-arsenal.com for tooltips, but if i wanted to create my own custom View, how should I go about this? I want to avoid having to draw to the Canvas to create the tooltip. At the moment I have the content in one view and the arrow in another view. I want to position the arrow either on top or on bottom of the content, and i want to position it a percentage distance from the left or right. I was thinking of using ConstraintLayouts and horizontal biases. Am i on the right track?
    :not-kotlin: 2
    b
    • 2
    • 17
  • h

    Hovhannes

    07/16/2021, 8:52 AM
    Hello everybody, What is the reason of this error?  And how can I fix it?   " FATAL EXCEPTION: OkHttp Dispatcher     Process: net.simplifiedcoding, PID: 13491     kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized" in Fragment
    fun reqBody(): RequestBody {
        val clientIdentifier = binding.edittxtClientIdentifier.text.toString().trim()
        val device = binding.edittxtDeviceType.text.toString().trim()
    
        val lang = binding.edittxtLang.text.toString().trim()
        val partn = binding.edittxtPartnerId.text.toString().trim()
        val pass = binding.editTextTextPassword.text.toString().trim()
        viewModel.login(
            clientIdentifier,
            Integer.parseInt(device),
            lang,
            Integer.parseInt(partn),
            pass
        )
    
    
    
        val rootObject = JSONObject()
        rootObject.put("ClientIdentifier", clientIdentifier)
        rootObject.put("DeviceType", device)
        rootObject.put("LanguageId", lang)
        rootObject.put("PartnerId", partn)
        rootObject.put("Password", pass)
        encrypt(rootObject.toString(), publicKey)
    
        val encrypted = encrypt(rootObject.toString(), publicKey)
        return RequestBody.create(
            "application/json; charset=utf-8".toMediaTypeOrNull(),
            "{\r\n    \"Data\":\"$encrypted\"\r\n}"
        )
    }
    In another class
    private fun <Request> getRetrofitClient(authenticator: Authenticator? = null): OkHttpClient {
    
        return OkHttpClient.Builder()
            .addInterceptor { chain ->
                chain.proceed(chain.request().newBuilder().also {
                    it.addHeader("Accept", "application/json")
                    it.method("POST", LoginFragment().reqBody())      //Error shows on this
    
                }.build())
            }.also { client ->
                authenticator?.let { client.authenticator(it) }
                if (BuildConfig.DEBUG) {
                    val logging = HttpLoggingInterceptor()
                    logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                    client.addInterceptor(logging)
                }
            }.build()
    
    }
    v
    • 2
    • 9
  • b

    brandonmcansh

    07/16/2021, 2:44 PM
    Hey guys hitting an issue trying to inject into a Worker with Hilt 🧵
    n
    z
    • 3
    • 16
  • a

    althaf

    07/17/2021, 1:26 PM
    hi all, is this right way to declare dependency for coroutine dispatcher using KOIN , i'm worried about this as Dispatcher.IO and Dispatcher.Default are of same type while Main is of different type. This might be ambiguous
    val diCoroutineModule = module {
        single { <http://Dispatchers.IO|Dispatchers.IO>  }
        single { Dispatchers.Main }
        single { Dispatchers.Default }
    }
    Something similar ins HILT
    @InstallIn(SingletonComponent::class)
    @Module
    object CoroutinesModule {
    
        @DefaultDispatcher
        @Provides
        fun providesDefaultDispatcher(): CoroutineDispatcher = Dispatchers.Default
    
        @IoDispatcher
        @Provides
        fun providesIoDispatcher(): CoroutineDispatcher = <http://Dispatchers.IO|Dispatchers.IO>
    
        @MainDispatcher
        @Provides
        fun providesMainDispatcher(): CoroutineDispatcher = Dispatchers.Main
    
        @MainImmediateDispatcher
        @Provides
        fun providesMainImmediateDispatcher(): CoroutineDispatcher = Dispatchers.Main.immediate
    }
    b
    k
    • 3
    • 22
  • j

    Jason Inbody

    07/17/2021, 9:51 PM
    Are there any kotlin libraries like SwiftyJSON for swift. I'm looking at JSON parsing libraries and they all seem to need a defined class to parse json strings to. SwiftyJSON was pretty useful as I didnt need to declare data classes and could just build objects from http responses with out having to decode each request i made. Ah looks like i can do it with
    Klaxon().parse<Map<String,Any>>(jsonString)!!
    or
    var map: Map<String, Any> = HashMap()
    map = Gson().fromJson(jsonString, map.javaClass)
    l
    e
    +2
    • 5
    • 8
  • w

    Waqas Tahir

    07/18/2021, 2:08 PM
    I know this is off topic but does anyone know names of these icons / where to find them , I've tried everywhere
    z
    c
    • 3
    • 4
  • a

    alorma

    07/19/2021, 11:44 AM
    Hi all! Anyone know a library to work with android contacts, or at least a good example / tutorial? I've found a blog post on how to load a list fast, but it's only for phones / emails, and contacts app has labels, address, connections (duo, whatsapp)... and I cannot find an easy solution that provides all info
    :google: 2
    i
    • 2
    • 5
  • h

    Hovhannes

    07/19/2021, 12:35 PM
    Hello, everybody, I've a question, but it's a little bit difficult. I get an error " kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized". binding cannot initialized in getRetrofitClient(). Is there any way or other technologies to fix this issue? Thanks in advance.
    class LoginFragment : Fragment() {
    
        private lateinit var binding: FragmentLoginBinding
        private val viewModel: AuthViewModel by viewModels()
        /* private val viewModel:AuthViewModel by lazy{
             ViewModelProvider(this).get(AuthViewModel::class.java)
    
         }*/
    
    
    
        @RequiresApi(Build.VERSION_CODES.O)
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            binding = FragmentLoginBinding.inflate(inflater, container, false)
         ........
       }
    
      fun reqBody(): String {
    
            Log.d("LogFrag", "reqBody's binding$binding")
    
            val clientIdentifier = binding.edittxtClientIdentifier.text.toString().trim()
           
            val pass = binding.editTextTextPassword.text.toString().trim()
    
            viewModel.login(
                clientIdentifier,
                pass
            )
    
            val rootObject = JSONObject()
            rootObject.put("ClientIdentifier", clientIdentifier)
            rootObject.put("Password", pass)
            encrypt(rootObject.toString(), publicKey)
    
            val encrypted = encrypt(rootObject.toString(), publicKey)
    
            return encrypted
        }
    fun <Request> getRetrofitClient(authenticator: Authenticator? = null): OkHttpClient {
     
        val finalEncr=reqBody()                //Error shows on this
          
        val body = "{\r\n    \"Data\":\"$finalEncr\"\r\n}"
            .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
    
    
        return OkHttpClient.Builder()
            .addInterceptor { chain ->
                chain.proceed(chain.request().newBuilder().also {
                    it.addHeader("Accept", "application/json")
                    it.method("POST", body)
    
                }.build())
            }.also { client ->
                authenticator?.let { client.authenticator(it) }
                if (BuildConfig.DEBUG) {
                    val logging = HttpLoggingInterceptor()
                    logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                    client.addInterceptor(logging)
                }
            }.build()
    }
    :thread-please: 4
    i
    • 2
    • 1
  • a

    atanasi charle

    07/19/2021, 3:45 PM
    Hey guys!.. Please can you suggest a way on how to pass object in navigation compose
    z
    c
    h
    • 4
    • 4
  • k

    Ketan Khunti

    07/20/2021, 3:57 AM
    I defined onClick="internal" in button and when I use fun internal(v:VIEW) {} then it is working but when I define function like fun internal() {} then it isn't working. Can anyone explain why it is so ?
    :not-kotlin: 4
    d
    e
    • 3
    • 4
  • c

    Ciprian Grigor

    07/20/2021, 11:22 AM
    Trying use paging 3 lib with filter I cannot explain why it crashed if I don’t insert in between .cachedIn(viewModelScope)
    val repoResult: Flow<PagingData<Repo>> = queryFlow.filterNotNull()
            .flatMapLatest { query ->
                repository.getSearchResultStream(query)
            }
            //.cachedIn(viewModelScope) //crash without
            .combine(filterFlow) { page, filter ->
                page.filter {
                    it.description?.contains(filter, true) ?: false
                }
            }
    
        lifecycleScope.launch {
                viewModel.repoResult.collectLatest {
                    adapter.submitData(it)
                }
        }
    
    crash is java.lang.IllegalStateException: Attempt to collect twice from pageEventFlow, which is an illegal operation. Did you forget to call Flow<PagingData<*>>.cachedIn(coroutineScope)?
    i
    • 2
    • 2
  • h

    Hovhannes

    07/20/2021, 2:11 PM
    Hello, everybody, I've a question. I get an error " kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized".  binding cannot initialized in getRetrofitClient().  What mistake did I make? Or there any way or other technologies to fix this issue?  If I don't use the 2nd line of getRetrofitClient(), the app works. Thanks in advance.
    lass LoginFragment : Fragment() {
    
        private lateinit var binding: FragmentLoginBinding
        private val viewModel: AuthViewModel by viewModels()
        /* private val viewModel:AuthViewModel by lazy{
             ViewModelProvider(this).get(AuthViewModel::class.java)
         }*/
    
        @RequiresApi(Build.VERSION_CODES.O)
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            binding = FragmentLoginBinding.inflate(inflater, container, false)
         ........
          return binding.root
       }
    
      fun reqBody(): String {
    
            Log.d("LogFrag", "reqBody's binding$binding")
    
            val clientIdentifier = binding.edittxtClientIdentifier.text.toString().trim()
    
            val pass = binding.editTextTextPassword.text.toString().trim()
    
            viewModel.login(
                clientIdentifier,
                pass
            )
    
            val rootObject = JSONObject()
            rootObject.put("ClientIdentifier", clientIdentifier)
            rootObject.put("Password", pass)
            encrypt(rootObject.toString(), publicKey)
    
            val encrypted = encrypt(rootObject.toString(), publicKey)
    
            return encrypted
        }
    
    
    
    fun <Request> getRetrofitClient(authenticator: Authenticator? = null): OkHttpClient {
    
        val finalEncr=reqBody()                //Error shows on this
    
        val body = "{\r\n    \"Data\":\"$finalEncr\"\r\n}"
            .toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
    return OkHttpClient.Builder()
            .addInterceptor { chain ->
                chain.proceed(chain.request().newBuilder().also {
                    it.addHeader("Accept", "application/json")
                    it.method("POST", body)
    
                }.build())
            }.also { client ->
                authenticator?.let { client.authenticator(it) }
                if (BuildConfig.DEBUG) {
                    val logging = HttpLoggingInterceptor()
                    logging.setLevel(HttpLoggingInterceptor.Level.BODY)
                    client.addInterceptor(logging)
                }
            }.build()
    }
    class RemoteDataSource {
    
        @RequiresApi(Build.VERSION_CODES.O)
        fun <Api> buildApi(
            api: Class<Api>,
            context: Context
        ): Api {
    
            val authenticator = TokenAuthenticator(context, buildTokenApi())
            Log.d("RemoteDataSource", "buildApi")
    
            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(LoginFragment().getRetrofitClient<Any>(authenticator))
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(api)
        }
    @RequiresApi(Build.VERSION_CODES.O)
        fun buildTokenApi(): TokenRefreshApi {
            Log.d("RemoteDataSource", "buildTokenApi")
    
            return Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(LoginFragment().getRetrofitClient<Any>())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(TokenRefreshApi::class.java)
        }
    
    }
    l
    j
    +2
    • 5
    • 6
  • j

    Jon

    07/20/2021, 7:24 PM
    I have a function that returns a live data such as
    fun getLiveData(): LiveData<Result?> { return mResult }
    where mResult is just a simple POJO. I am confused a bit about how kotlin interprets the return type for this function. I would imagine this to be non-null but when I try to call it, it forces me to use the null-safe operator "?.". If I wanted this to be nullable, I would imagine the return type would be
    LiveData<Result?>?
    with the appended "?"
    c
    z
    • 3
    • 4
  • h

    Hovhannes

    07/21/2021, 12:56 PM
    Hello, everybody, I've a question. I need that getUser() receives argument only from an EditText's value.  How can I do it? Using SharedPreferences?  Thanks in advance.
    interface AuthApi : BaseApi {
        @FormUrlEncoded
        @PUT("{PartnerId}/api/Main/LoginClient")
        suspend fun login(
            @Field("email") email: String,
            @Path("PartnerId") partnerId:String,
        ): LoginResponse
    }
    interface UserApi : BaseApi{
        @GET("{PartnerId}/api/Main/LoginClient")
        suspend fun getUser(@Path("PartnerId")partnerId:Int): LoginResponse
    }
    class UserRepository @Inject constructor(
        private val api: UserApi
    ) : BaseRepository(api) {
        suspend fun getUser() = safeApiCall { api.getUser(0) }    <---getUser()'s argument must be  EditText's value
    }
    :not-kotlin: 4
    :thread-please: 1
    i
    c
    • 3
    • 2
  • r

    rajesh

    07/22/2021, 6:07 AM
    How can we update single item in paging list (paging 3)? I wants to update paging list (like property of object) when user click on like button
    d
    • 2
    • 3
  • a

    André Thiele

    07/22/2021, 11:43 AM
    I am still getting this lint error even though I am using Fragment 1.3.6. Any ideas?
    t
    j
    i
    • 4
    • 8
  • p

    Pawan Gorai

    07/22/2021, 5:14 PM
    How can I use KMM in Android Studio with Windows 10 ? Because I can see the plugin available is only for macOS so can anyone tell how I can integrate KMM in my existing or new projects with Windows.
    j
    l
    +2
    • 5
    • 9
  • l

    Libor Bicanovsky

    07/22/2021, 9:20 PM
    Hey, is there a way to get rid of font padding within a Text element in jetpack compose? I have a Button and the text within it is slightly off center, which I assume is due to font padding. Is there an equivalent to includeFontPadding=false?
    c
    • 2
    • 1
Powered by Linen
Title
l

Libor Bicanovsky

07/22/2021, 9:20 PM
Hey, is there a way to get rid of font padding within a Text element in jetpack compose? I have a Button and the text within it is slightly off center, which I assume is due to font padding. Is there an equivalent to includeFontPadding=false?
c

Chris Fillmore

07/23/2021, 6:06 PM
Try asking in #compose
View count: 19