Proguard,无法创建类ViewModel kotlin的实例

时间:2018-08-29 13:06:47

标签: android android-lifecycle android-proguard

仅当minifyEnabled为true时,我才会收到该错误(即使使用-dontobfuscate)

java.lang.RuntimeException: Cannot create an instance of class com.myapps.app.TracksVM
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:202)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
        at com.myapps.app.MyFragment.onCreateView(MyFragment.kt:72)
支持库源代码中的

ViewModelProvider.java:202指的是:

try {
                    return modelClass.getConstructor(Application.class).newInstance(mApplication);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                }

Proguard可能删除了方法或构造函数?

这是我的proguard.pro:

-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
-dontwarn org.conscrypt.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontobfuscate

ViewModel:

class TracksVM(application: Application) : AndroidViewModel(application) {
...
}

还有片段:

class MyFragment : Fragment() {
    private lateinit var viewModel: TracksVM

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return inflater.inflate(R.layout.content_recents, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        viewModel = ViewModelProviders.of(this).get(TracksVM::class.java)
    }
}

2 个答案:

答案 0 :(得分:2)

您没有传递viewModelProviderFactory-

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    viewModel = ViewModelProviders.of(this,viewModelProvidersFactory).get(TracksVM::class.java)
}

我希望这会对您有所帮助。

答案 1 :(得分:0)

Android生命周期aar的消费者Proguard规则中缺少以下规则:

-keepclassmembers,allowshrinking,allowobfuscation class * extends android.arch.lifecycle.AndroidViewModel {
    <init>(android.app.Application);
}

使用最新版本(androidx?)时,应该将其修复。