skip to Main Content

Hello I’m creating photo album app using room database. But when I run the app I got an error that says can not create instance of the viewmodel class. Your assistance will highly be appreciated.
here is the logcat

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.photoalbum/com.example.photoalbum.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.photoalbum.MyImagesVIewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.photoalbum.MyImagesVIewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:236)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:171)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:139)
at com.example.photoalbum.MainActivity.onCreate(MainActivity.java:35)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:228)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:171) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:139) 
at com.example.photoalbum.MainActivity.onCreate(MainActivity.java:35) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
Caused by: 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.(MyImagesRepository.java:19)
at com.example.photoalbum.MyImagesVIewModel.(MyImagesVIewModel.java:22)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:228) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:171) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:139) 
at com.example.photoalbum.MainActivity.onCreate(MainActivity.java:35) 
at android.app.Activity.performCreate(Activity.java:8000) 
at android.app.Activity.performCreate(Activity.java:7984) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:223) 
at android.app.ActivityThread.main(ActivityThread.java:7656) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
2021-10-08 09:18:55.708 23415-23415/com.example.photoalbum I/Process: Sending signal. PID: 23415 SIG: 9

here is the Viewmodel class

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;
        }
    }
}

here is my mainactivity

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);
            }
        });

    }
}

here is my repository class

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;
        }
    }
}

2

Answers


  1. This is happening because of the NullPointerExcepion in the ViewModel constructor.

    You see the in the logs.

    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.
    

    In your repository class

    public MyImagesRepository(Application application){
            MyImagesDatabase database = MyImagesDatabase.getInstance(application);
            myImagesDAO = database.myImagesDAO(); //here database seems to be null.
            imagesList = myImagesDAO.getAllImages();
        }
    
    Login or Signup to reply.
  2. Maybe there is something wrong in the constructor of your viewmodel. Try this constructor-

      myImagesVIewModel=new ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())).get( MyImagesVIewModel.class);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search