当前位置: 首页 > 知识库问答 >
问题:

无法创建ViewModel类的实例

喻选
2023-03-14
package com.example.photoalbum;

import android.app.Application;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProvider;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;

import java.util.List;

public class MyImagesVIewModel extends AndroidViewModel {

     private MyImagesRepository repository;
     private LiveData<List<MyImages>> imageList;
    public MyImagesVIewModel(@NonNull Application application) {
        super(application);
        repository = new MyImagesRepository(application);
        imageList = repository.getAllImages();
    }

    public void insert(MyImages myImages){
        repository.insert(myImages);
    }

    public void delete(MyImages myImages){
        repository.delete(myImages);
    }

    public void update(MyImages myImages){
        repository.update(myImages);
    }

    public LiveData<List<MyImages>> getAllImages(){
        return imageList;
    }
}

here is my repository classs

package com.example.photoalbum;

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

import androidx.lifecycle.LiveData;

import java.util.ArrayList;
import java.util.List;

public class MyImagesRepository {

    private MyImagesDAO myImagesDAO;
    private LiveData<List<MyImages>> imagesList;

    public MyImagesRepository(Application application){

        MyImagesDatabase database = MyImagesDatabase.getInstance(application);
        myImagesDAO = database.myImagesDAO();
        imagesList = myImagesDAO.getAllImages();
    }

    public void insert(MyImages myImages){

        new InsertImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public void delete(MyImages myImages){

        new DeleteImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public void update(MyImages myImages){

        new UpdateImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public LiveData<List<MyImages>> getAllImages(){

        return imagesList;
    }

    public static class InsertImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public InsertImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.insert(myImages[0]);
            return null;
        }
    }

    public static class DeleteImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public DeleteImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.delete(myImages[0]);
            return null;
        }
    }

    public static class UpdateImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public UpdateImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.update(myImages[0]);
            return null;
        }
    }
}
package com.example.photoalbum;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    private MyImagesVIewModel myImagesVIewModel;
    private RecyclerView rv;
    private FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv = findViewById(R.id.rv);
        fab = findViewById(R.id.fab);
        rv.setLayoutManager(new LinearLayoutManager(this));
        MyImagesAdapter adapter = new MyImagesAdapter();
        rv.setAdapter(adapter);
        myImagesVIewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication())
                    .create(MyImagesVIewModel.class);
        //ViewModelProvider.Factory
        // which may create AndroidViewModel and ViewModel, which have an empty constructor.
        myImagesVIewModel.getAllImages().observe(MainActivity.this, new Observer<List<MyImages>>() {
            @Override
            public void onChanged(List<MyImages> myImages) {//called when data is changed

                adapter.setImagesList(myImages);
            }
            //observer updates the UI
        });

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MainActivity.this, AddImageActivity.class);
                startActivityForResult(intent, 3);
            }
        });

    }
}
package com.example.photoalbum;

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

import androidx.lifecycle.LiveData;

import java.util.ArrayList;
import java.util.List;

public class MyImagesRepository {

    private MyImagesDAO myImagesDAO;
    private LiveData<List<MyImages>> imagesList;

    public MyImagesRepository(Application application){

        MyImagesDatabase database = MyImagesDatabase.getInstance(application);
        myImagesDAO = database.myImagesDAO();
        imagesList = myImagesDAO.getAllImages();
    }

    public void insert(MyImages myImages){

        new InsertImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public void delete(MyImages myImages){

        new DeleteImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public void update(MyImages myImages){

        new UpdateImageAsyncTask(myImagesDAO).execute(myImages);
    }

    public LiveData<List<MyImages>> getAllImages(){

        return imagesList;
    }

    public static class InsertImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public InsertImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.insert(myImages[0]);
            return null;
        }
    }

    public static class DeleteImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public DeleteImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.delete(myImages[0]);
            return null;
        }
    }

    public static class UpdateImageAsyncTask extends AsyncTask<MyImages,Void,Void>{

        MyImagesDAO myImagesDAO;

        public UpdateImageAsyncTask(MyImagesDAO myImagesDAO) {
            this.myImagesDAO = myImagesDAO;
        }

        @Override
        protected Void doInBackground(MyImages... myImages) {
            myImagesDAO.update(myImages[0]);
            return null;
        }
    }
}

共有1个答案

童浩言
2023-03-14

发生这种情况是因为viewmodel构造函数中的NullPointerException

你在日志里看到了。

java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.photoalbum.MyImagesDAO com.example.photoalbum.MyImagesDatabase.myImagesDAO()' on a null object reference at com.example.photoalbum.MyImagesRepository.

存储库类中

public MyImagesRepository(Application application){
        MyImagesDatabase database = MyImagesDatabase.getInstance(application);
        myImagesDAO = database.myImagesDAO(); //here database seems to be null.
        imagesList = myImagesDAO.getAllImages();
    }
 类似资料:
  • 这是我的代码 这是从谷歌样本..后我想: 问题就在这里: java.lang.RuntimeException:无法创建类com.lacas.db.room.BookMarkViewModel的实例 我可以用这个片段吗? null

  • 你好,我是android中MVVM的新手,正在使用livedata。我正在尝试创建viewmodel的一个实例。我觉得问题在于我没有将存储库传递给viewmodel构造函数。我一直无法创建viewmodel的实例。我不知道该怎么做这里是我的viewmodel和它的创建。

  • 我尝试了MVVM架构,实现了所有需要的类和方法。在MainActivity中创建ViewModel类的对象时,我得到以下错误的实例。 我试了一个YouTube教程中的例子。我把所有的实现都做对了。我尝试过将ViewModel类和构造函数公开,但应用程序仍然在运行时崩溃。 mainactivity.java NoteViewModel.java noteRepository.java 日志

  • 我正在开发一本新书android应用程序,但当我测试从logcat获取以下异常的代码时,应用程序崩溃 hread.mainRuntimeException:无法启动活动ComponentInfo{hread.java:6662}:java.lang.reflect.RuntimeException:无法创建ethod.invokeBookViewModel类的实例com.android.inter

  • 我只是从喷气背包和剑柄开始。但是当我注入到ViewModel中时,我遇到了一些问题。 我得到的错误: 我可以在活动中注入所有细节,但不能在ViewModel中注入。我已经尝试了所有我能找到的解决办法。 我的gradle文件: 项目根级别: 模块级: 我的申请文件 我的模块文件: 项目是具有可组合屏幕的单个活动,因此主要活动: 视图模型: 我尝试过的事情: 改为ViewModelComponent而

  • 问题内容: 我希望能够通过在已实例化的对象上调用方法来创建对象的新实例。例如,我有一个对象: 我希望能够调用并拥有两个有机体类型的对象。此时我的方法如下所示: 并且我非常确定它不起作用(我甚至不确定如何测试它。我在本文中尝试了gc方法)。那么,如何使我的对象创建自己的副本,就像我创建的第一个对象(带有)一样,该副本是可访问的? 问题答案: 另一个选项-如果方法中未使用实例(): 这样可以确保生物产