Android ViewModelProvider.Factory:引起:java.lang.RuntimeException:无法创建类GameViewModel的实例

时间:2018-02-13 19:24:23

标签: android mvvm kotlin android-architecture-components android-viewmodel

我正在尝试创建一个ViewModelFactory来创建我的ViewModel。

工厂类是:

class GameViewModelFactory(private val application: GameApplication) : ViewModelProvider.Factory {
    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(GameViewModel::class.java)) {
            return GameViewModel(application) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

我也尝试从ViewModelProvider.AndroidViewModelFactory(application)延伸,但结果是一样的。

ViewModel类的构造函数是:

class GameViewModel(private val gameApplication: GameApplication) : AndroidViewModel(gameApplication)

我在片段中完全称呼它的方式如下:

val remoteViewModelFactory = GameViewModelFactory(GameApplication())
        gameViewModel = ViewModelProviders
                .of(this, remoteViewModelFactory)
                .get(GameViewModel::class.java)

问题在于它似乎没有得到它,我认为可能是因为Application对象。 我已经尝试在我的GameApplication类中创建一个单例,但它仍然是相同的:

Caused by: java.lang.RuntimeException: Cannot create an instance of class trate.data.viewmodel.GameViewModel
    at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:133)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:101)
    at trate.ui.game.GameFragment.onCreate(GameFragment.kt:70)

非常感谢!

编辑:如果我调试并进入VieWModelProvider类,我看到它到达AndroidViewModelFactory类并进入get创建方法。 然后它会尝试返回modelClass.getConstructor(Application.class).newInstance(mApplication),但随后会抛出以下RuntimeException

result = {NoSuchMethodException@5072} "java.lang.NoSuchMethodException: <init> [class android.app.Application]"
 backtrace = {Object[32]@5085} 
 cause = {NoSuchMethodException@5072} "java.lang.NoSuchMethodException: <init> [class android.app.Application]"
 detailMessage = "<init> [class android.app.Application]"
 stackTrace = {StackTraceElement[0]@5087} 
 suppressedExceptions = {Collections$EmptyList@5088}  size = 0
 shadow$_klass_ = {Class@3232} "class java.lang.NoSuchMethodException"
 shadow$_monitor_ = -2097726229

0 个答案:

没有答案