https://kotlinlang.org logo
#android
Title
# android
n

Nikola Milovic

12/03/2019, 9:56 AM
Copy code
Type inference failed: fun <T : Any!> getSystemService(context: Context, serviceClass: Class<T!>): T?
cannot be applied to
(String)
Copy code
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
Copy code
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
Copy code
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
68 Views