无法创建类 com.example.architectureexample.NoteViewModel 的实例 [英] Cannot create an instance of class com.example.architectureexample.NoteViewModel

查看:16
本文介绍了无法创建类 com.example.architectureexample.NoteViewModel 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

every time i run my app it shows this error in the title and i have searched for the problem some said make the ViewModel constructor public and mine is public other said Either:

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

Remove the Context context and LifecycleOwner lifecycleOwner constructor parameters from your HomeViewModel, or

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

Create a ViewModelProvider.Factory that can build your HomeViewModel instances, and use that factory with ViewModelProviders.of()

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

and i have made the two solutions and still get the same error

主活动

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 类

ViewModel class

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 接口

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) 

推荐答案

您的数据库从未初始化.

Your database is never initialized.

instance!=null 应该是 instance==null.

这篇关于无法创建类 com.example.architectureexample.NoteViewModel 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆