gpt4 book ai didi

java - 无法创建 com.example.architectureexample.NoteViewModel 类的实例

转载 作者:行者123 更新时间:2023-12-02 00:35:23 27 4
gpt4 key购买 nike

每次我运行我的应用程序时,它都会在标题中显示此错误我已经搜索了一些人说的将 ViewModel 构造函数公开而我的问题是公开的其他人说要么:

从 HomeViewModel 中删除 Context 上下文和 LifecycleOwnerlifecycleOwner 构造函数参数,或者

创建一个可以构建 HomeViewModel 实例的 ViewModelProvider.Factory,并将该工厂与 ViewModelProviders.of() 一起使用

我已经做了两个解决方案,但仍然得到相同的错误

主要 Activity

package com.example.architectureexample;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import android.os.Bundle;
import android.widget.Toast;

import java.util.List;

public class MainActivity extends AppCompatActivity {
// 5th video
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) {
// update recycleView
Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
}
});
}
}

ViewModel 类

package com.example.architectureexample;
// 5th video
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;

import java.util.List;

public class NoteViewModel extends AndroidViewModel {

private NoteRep rep;
private LiveData<List<Note>> allNotes;

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

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

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

public void delete(Note note){
rep.delete(note);
}

public void deleteAll(){
rep.deleteAll();
}

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

存储库类

package com.example.architectureexample;

// 4th video

import android.app.Application;
import android.os.AsyncTask;

import androidx.lifecycle.LiveData;

import java.util.List;

public class NoteRep {

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

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

// these methods works as API the the Repository Exports to the out side
public void insert(Note note){
new InsertNoteAsyncTask(noteDao).execute(note);
}

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

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

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

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

private static class InsertNoteAsyncTask extends AsyncTask<Note ,Void,Void>{
// we need it to do database operations
private NoteDao noteDao;

// because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
public 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>{
// we need it to do database operations
private NoteDao noteDao;

// because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
public 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>{
// we need it to do database operations
private NoteDao noteDao;

// because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
public 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>{
// we need it to do database operations
private NoteDao noteDao;

// because the class is static we can't access the NoteDao directly so we have to pass it throw a constructor
public DeleteAllNotesAsyncTask(NoteDao noteDao) {
this.noteDao = noteDao;
}


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

}

}

数据库类

package com.example.architectureexample;

// 3rd video
// this is a class where we connect the database table with the dao to get the to communicate with each other
import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

@Database(entities = {Note.class},version = 1)
public abstract class NoteDatabase extends RoomDatabase {
private static NoteDatabase instance;

// this will access our Dao
public abstract NoteDao noteDao();

public static synchronized NoteDatabase getInstance(Context context){
if(instance!=null){
instance = Room.databaseBuilder(context.getApplicationContext(),
NoteDatabase.class,"note_database")
.fallbackToDestructiveMigration()
// added call back 4th video
.addCallback(roomCallback)
.build();
}
return instance;
}

// 4th video
private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);

new PopulateDbAsyncTask(instance).execute();

}
};

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

private NoteDao noteDao;

private PopulateDbAsyncTask(NoteDatabase database){
noteDao = database.noteDao();
}

@Override
protected Void doInBackground(Void... voids) {
noteDao.insert(new Note("Title1","des1",1));
noteDao.insert(new Note("Title2","des2",2));
noteDao.insert(new Note("Title3","des3",3));
return null;
}
}
}

表类

package com.example.architectureexample;
// 2nd video
// this is the database table
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity(tableName = "note_table")
public class Note {

@PrimaryKey(autoGenerate = true)
private int id;
private String title ;
private String description;
private int priorty;

public Note(String title, String description, int priorty) {
this.title = title;
this.description = description;
this.priorty = priorty;
}

public void setId(int id) {
this.id = id;
}

public int getId() {
return id;
}

public String getTitle() {
return title;
}

public String getDescription() {
return description;
}

public int getPriorty() {
return priorty;
}
}

DAO 接口(interface)

package com.example.architectureexample;

import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Update;

// 3rd video
// this is the dao that will interact with the databse to get the data

import java.util.List;

@Dao
public interface NoteDao {
@Insert
void insert(Note note);

@Update
void update(Note note);

@Delete
void delete(Note note);

// sql code delete from (table name)
@Query("DELETE FROM note_table")
void deleteAllNotes();

@Query("SELECT * FROM note_table ORDER BY priorty DESC")
LiveData<List<Note>> getAllNotes();

}

logcat 错误

2019-09-18 17:38:07.042 15476-15476/com.example.architectureexample E/Minikin: Could not get cmap table size!
2019-09-18 17:38:07.088 15476-15497/com.example.architectureexample E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
2019-09-18 17:38:07.373 15476-15476/com.example.architectureexample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.architectureexample, PID: 15476
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.architectureexample/com.example.architectureexample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.architectureexample.NoteViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3303)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411)
at android.app.ActivityThread.-wrap12(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.architectureexample.NoteViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:238)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130)
at com.example.architectureexample.MainActivity.onCreate(MainActivity.java:22)
at android.app.Activity.performCreate(Activity.java:7383)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
at android.app.ActivityThread.-wrap12(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
at android.os.Handler.dispatchMessage(Handler.java:108) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7529) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
at com.example.architectureexample.MainActivity.onCreate(MainActivity.java:22) 
at android.app.Activity.performCreate(Activity.java:7383) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
at android.app.ActivityThread.-wrap12(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
at android.os.Handler.dispatchMessage(Handler.java:108) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7529) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.architectureexample.NoteDao com.example.architectureexample.NoteDatabase.noteDao()' on a null object reference
at com.example.architectureexample.NoteRep.<init>(NoteRep.java:19)
at com.example.architectureexample.NoteViewModel.<init>(NoteViewModel.java:18)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:230) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:164) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:130) 
at com.example.architectureexample.MainActivity.onCreate(MainActivity.java:22) 
at android.app.Activity.performCreate(Activity.java:7383) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3256) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3411) 
at android.app.ActivityThread.-wrap12(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
at android.os.Handler.dispatchMessage(Handler.java:108) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7529) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 

最佳答案

您的数据库从未初始化。

instance!=null 应为 instance==null

关于java - 无法创建 com.example.architectureexample.NoteViewModel 类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57982050/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com