如何修复“无法创建ViewModel类的实例”?

时间:2019-06-02 04:10:12

标签: java android mvvm android-jetpack

我尝试使用MVVM架构,实现了所有必需的类和方法。在MainActivity中创建ViewModel类的对象时,出现此错误java.lang.RuntimeException: Cannot create an instance of class com.prathameshmore.getnotes.viewmodel.NoteViewModel

我尝试了YouTube教程中的示例。我做了所有正确的实施。我尝试将ViewModel类和构造函数公开,但仍然使应用程序在运行时崩溃。

MainActivity.java

`公共类MainActivity扩展了AppCompatActivity {

private NoteViewModel noteViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
    noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
        @Override
        public void onChanged(List<Note> notes) {
            Toast.makeText(MainActivity.this, "Updated", Toast.LENGTH_SHORT).show();
        }
    });

}

} `

NoteViewModel.java

`公共类NoteViewModel扩展了AndroidViewModel {

private NoteRepository noteRepository;
private LiveData<List<Note>> allNotes;

public NoteViewModel(@NonNull Application application) {
    super(application);
    noteRepository = new NoteRepository(application);
    allNotes = noteRepository.getAllNotes();
}

public void insert(Note note) {
    noteRepository.insert(note);
}

public void update(Note note) {
    noteRepository.update(note);
}

public void delete(Note note) {
    noteRepository.delete(note);

}

public void deleteAllNotes() {
    noteRepository.deleteAllNotes();
}

public LiveData<List<Note>> getAllNotes() {
    return allNotes;
}

}`

NoteRepository.java

`公共类NoteRepository {

private NoteDao noteDao;
private LiveData<List<Note>> allNotes;

public NoteRepository(Application application) {
    NoteDatabase database = NoteDatabase.getInstance(application);
    noteDao = database.noteDao();
    allNotes = noteDao.getAllNotes();
}

public void insert(Note note){
    new InsertNoteAsyncTask(noteDao).execute(note);
}

public void delete(Note note) {
    new DeleteNoteAsyncTask(noteDao).execute(note);
}

public void update(Note note) {
    new UpdateNoteAsyncTask(noteDao).execute(note);
}

public void deleteAllNotes() {
    new DeleteAllNotesAsyncTask(noteDao).execute();
}

public LiveData<List<Note>> getAllNotes() {
    return allNotes;
}

private static class InsertNoteAsyncTask extends AsyncTask<Note, Void, Void> {

    private NoteDao noteDao;

    private InsertNoteAsyncTask(NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Note...notes) {
        noteDao.insert(notes[0]);
        return null;
    }
}

private static class UpdateNoteAsyncTask extends AsyncTask<Note, Void, Void> {

    private NoteDao noteDao;

    private UpdateNoteAsyncTask(NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Note...notes) {
        noteDao.update(notes[0]);
        return null;
    }
}

private static class DeleteNoteAsyncTask extends AsyncTask<Note, Void, Void> {

    private NoteDao noteDao;

    private DeleteNoteAsyncTask(NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Note...notes) {
        noteDao.delete(notes[0]);
        return null;
    }
}

private static class DeleteAllNotesAsyncTask extends AsyncTask<Void, Void, Void> {

    private NoteDao noteDao;

    private DeleteAllNotesAsyncTask(NoteDao noteDao) {
        this.noteDao = noteDao;
    }

    @Override
    protected Void doInBackground(Void...voids) {
        noteDao.deleteAllNotes();
        return null;
    }
}

}`

日志

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.prathameshmore.getnotes, PID: 28833 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.prathameshmore.getnotes/com.prathameshmore.getnotes.views.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.prathameshmore.getnotes.viewmodel.NoteViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2723) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784) at android.app.ActivityThread.-wrap12(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:163) at android.app.ActivityThread.main(ActivityThread.java:6238) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.prathameshmore.getnotes.viewmodel.NoteViewModel at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:208) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103) at com.prathameshmore.getnotes.views.MainActivity.onCreate(MainActivity.java:25) at android.app.Activity.performCreate(Activity.java:6868) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:163)  at android.app.ActivityThread.main(ActivityThread.java:6238)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)  Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.newInstance0(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:430) at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)  at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)  at com.prathameshmore.getnotes.views.MainActivity.onCreate(MainActivity.java:25)  at android.app.Activity.performCreate(Activity.java:6868)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:163)  at android.app.ActivityThread.main(ActivityThread.java:6238)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)  Caused by: java.lang.RuntimeException: cannot find implementation for com.prathameshmore.getnotes.database.NoteDatabase. NoteDatabase_Impl does not exist at androidx.room.Room.getGeneratedImplementation(Room.java:94) at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:851) at com.prathameshmore.getnotes.database.NoteDatabase.getInstance(NoteDatabase.java:31) at com.prathameshmore.getnotes.repository.NoteRepository.<init>(NoteRepository.java:20) at com.prathameshmore.getnotes.viewmodel.NoteViewModel.<init>(NoteViewModel.java:21) at java.lang.reflect.Constructor.newInstance0(Native Method)  at java.lang.reflect.Constructor.newInstance(Constructor.java:430)  at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)  at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)  at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)  at com.prathameshmore.getnotes.views.MainActivity.onCreate(MainActivity.java:25)  at android.app.Activity.performCreate(Activity.java:6868)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2676)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2784)  at android.app.ActivityThread.-wrap12(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1523)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:163)  at android.app.ActivityThread.main(ActivityThread.java:6238)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)  Application terminated.

4 个答案:

答案 0 :(得分:2)

这可以正常工作:

1。转到您的build.gradle(Module:app)并将其添加到依赖项中:

`implementation "android.arch.lifecycle:extensions:$lifecycle_version"`  

请确保您的依赖项中包含def lifecycle_version = "2.2.0"
所以它应该看起来像这样:

dependencies {

    def lifecycle_version = "2.2.0"  //make sure to have this 

    //Some implementations ...  

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


    implementation "android.arch.lifecycle:extensions:$lifecycle_version" // make sure to have this too.

}  

2。转到“活动”(在您的情况下为MainActivity),并输入以下行:

noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);  

因此您的MainActivity.java应该如下所示:

public class MainActivity extends AppCompatActivity {

private NoteViewModel noteViewModel;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
    noteViewModel.getAllNotes().observe(this, new Observer<List<Note>>() {
        @Override
        public void onChanged(List<Note> notes) {
            Toast.makeText(MainActivity.this, "Update, Enjoy coding :)", Toast.LENGTH_SHORT).show();
        }
    });

}
}

3。运行您的应用。

答案 1 :(得分:2)

放入

noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);

代替

new ViewModelProvider(this).get(mainActivityViewModel.class);

答案 2 :(得分:1)

考虑到CBS的答案,如2.3.0-alpha01更新 lifecycle-extensions 工件不再发布。

Lifecycle Documentation

依赖项

struct Node *Bucket[10] = {0};

AndroidViewModel类

def lifecycle_version = "2.2.0"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
kapt "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

implementation "androidx.fragment:fragment-ktx:1.2.4"

在片段中

class TestVM (app : android.app.Application) : AndroidViewModel(app){
    //Code
}

答案 3 :(得分:0)

您需要为ViewModel创建一个工厂类。

public class MyViewModelFactory implements ViewModelProvider.Factory {
    private Application mApplication;
    private String mParam;


    public MyViewModelFactory(Application application, String param) {
        mApplication = application;
        mParam = param;
    }


    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        return (T) new MyViewModel(mApplication, mParam);
    }
}

当实例化视图模型时,您这样做:

MyViewModel myViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "my awesome param")).get(MyViewModel.class);