关于ViewModel使用的一个血案
2021-04-30 本文已影响0人
方可为友
关于ViewModel使用的一个血案: Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.demo043002.MainViewModel
在写一个关于ViewModel的demo,总是在运行期报错,百思不得其解:
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.demo043002.MainViewModel
at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:186)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.demo043002.MainActivity.onCreate(MainActivity.kt:14)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
代码很简单:
class MainViewModel extends ViewModel {
}
class MainActivity : AppCompatActivity() {
val TAG="MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val mainViewModel=ViewModelProvider(this,ViewModelProvider.NewInstanceFactory()).get(MainViewModel::class.java)
Log.e(TAG,"mainViewModel==null:"+(mainViewModel==null))
}
}
同志们,发现问题没???其实就是MainViewModel的权限没有用public!!!,教训惨重啊,又浪费了半天时间
image.png