Reputation: 27236
Toolchain:
Android Studio 3.0 Canary 2:
Build #AI-171.4041253, built on May 24, 2017 JRE: 1.8.0_112-release-b736 x86_64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Mac OS X 10.12.5
Google SDK/Tools: I have downloaded the latest "all" (Android O, tools, libraries, etc. at least according to Android Studio SDK Manager).
Problem: javaClass<>
is missing and Android Studio can't "import it".
What I did:
Create new Android project, target API 23 and told it to include a "basic activity".
Added the Gradle dependencies for ViewModel and Room taken from: https://developer.android.com/topic/libraries/architecture/adding-components.html
These are the lines I added to my App Module's gradle file:
compile "android.arch.lifecycle:runtime:1.0.0-alpha1"
compile "android.arch.lifecycle:extensions:1.0.0-alpha1"
annotationProcessor "android.arch.lifecycle:compiler:1.0.0-alpha1"
compile "android.arch.persistence.room:runtime:1.0.0-alpha1"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0-alpha1"
The Kotlin reference in the same Gradle is: compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
(I didn't add that one, came automatically)
I then created a simple Kotlin class called MainViewModel
:
import android.arch.lifecycle.ViewModel class MainViewModel : ViewModel() {}
Then I went to my Activity and tried to do what this Google Documentation says: https://developer.android.com/topic/libraries/architecture/viewmodel.html
It's in Java but converted to Kotlin, I think it should look like:
val mainViewModel = ViewModelProviders.of(this).get(javaClass<MainViewModel>)
The problem is that Android Studio is not finding javaClass and the fix (to press ⌥⏎) doesn’t do anything.
Upvotes: 2
Views: 2730
Reputation: 27236
I decided to try to use the Java To Kotlin conversion. So I created a new Activity in Java, and wrote the above code as the java documentation states.
After the class was working, I did Code -> Convert Java Class To Kotlin
in Android Studio, and the resulting Kotlin class had the following line:
val viewModel = ViewModelProviders.of(this).get(MainViewModel::class.java)
This compiled perfectly. I will have to learn more about which one is correct, but this one may save you some time if you’re, like me, new to the language.
Upvotes: 5