我尝试动手使用MVVM架构,我实现了所有必需的类和方法。在 MainActivity 中创建 ViewModel 类的对象时,我收到此错误java.lang.RuntimeException: Cannot create an instance of class com.prathameshmore.getnotes.viewmodel.NoteViewModel
。
我从YouTube教程中尝试了这个例子。我做了所有正确的实现。我尝试将 ViewModel 类和构造函数公开,但应用程序在运行时仍然崩溃。
主要活动.java
public class MainActivity extends 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();
}
});
}
}
注意视图模型.java
public class NoteViewModel extends 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;
}
}
注意存储库.java
public class 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/Android运行时:致命异常:main 进程: com.prathameshmore.getnotes, PID: 28833 java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.prathameshmore.getnotes/com.prathameshmore.getnotes.views.MainActivity}: java.lang.RuntimeException:无法创建类的实例 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) 原因:java.lang.RuntimeException:无法创建类 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) 由: 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) 原因:java.lang.RuntimeException:找不到 com.prathameshmore.getnotes.database.NoteDatabase 的实现。 NoteDatabase_Impl不存在 at androidx.room.Room.getGenerated Implementation(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.(注存储库.java:20) at com.prathameshmore.getnotes.viewmodel.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) 应用程序已终止。
你需要有一个工厂类来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);
这将正常工作:
1.转到您的build.gradle(模块:应用程序)并将其添加到依赖项中:
`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.运行您的应用程序。
把这个
noteViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(NoteViewModel.class);
而不是
new ViewModelProvider(this).get(mainActivityViewModel.class);
考虑到CBS的答案与2.3.0-alpha01更新生命周期扩展工件不再发布。
生命周期文档
依赖
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
}
在片段中
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewModel = ViewModelProvider(this).get(TestVM::class.java)
}
就我而言,我不小心将其放在项目 gradle 中,这会阻止或从项目中排除生命周期依赖项和视图模型。删除它
allprojects {
configurations.all {
resolutionStrategy.force "com.android.support:support-v4:26.1.0"
exclude group: 'androidx.lifecycle', module: 'lifecycle-viewmodel-ktx'
}
}