0

I'm getting a huge error when I start my app what follows is my ViewHolder and my main activity with my Error Code pls help don't understand why it gives me this error... I also know that this error message keeps on popping up but there is really no other way to handle it if you can't see what the trouble is then to ask so I'm both thankfull and sorry beforehand. Please tell me if you need more code I'm happy to help!:D

import android.app.Application;
import android.arch.lifecycle.AndroidViewModel;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class CustomerViewModel extends AndroidViewModel {

    private CustomerRepository mRepository;
    private LiveData<List<Customer>> mAllCustomers;


    public CustomerViewModel (Application application) {
        super(application);
        mRepository = new CustomerRepository(application);
        mAllCustomers = mRepository.getAllCustomers();
    }
    public LiveData<List<Customer>> getmAllCustomers() {

        return mAllCustomers;
    }
    public void insert(Customer customer){
        mRepository.insert(customer);

    }
    public void delete(Customer customer){

        mRepository.delete(customer);

    }






}

MainActivity: 

import android.arch.lifecycle.Observer;
    import android.arch.lifecycle.ViewModelProviders;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.design.widget.FloatingActionButton;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.Toolbar;
    import android.support.v7.widget.helper.ItemTouchHelper;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;



public class MainActivity extends AppCompatActivity {
    FloatingActionButton fab;
    private CustomerViewModel mCustomerViewModel;


    public static final int NEW_CUSTOMER_ACTIVITY_REQUEST_CODE = 1;



    private static final  String TAG = "MainActivity";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        RecyclerView recyclerView = findViewById(R.id.recycler);
        final List<Customer> savedList;

        final PapperRecyclerAdapter adapter = new PapperRecyclerAdapter(this);



        fab = findViewById(R.id.fab);

        mCustomerViewModel = ViewModelProviders.of(this).get(CustomerViewModel.class);

        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT ) {
            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {






            }
        }).attachToRecyclerView(recyclerView);





        mCustomerViewModel.getmAllCustomers().observe(this, new Observer<List<Customer>>() {
            @Override
            public void onChanged(@Nullable List<Customer> customers) {
                adapter.setCustomer(customers);
            }
        });

        recyclerView.setAdapter(adapter);
        fab.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CreateCustomer.class);
                startActivityForResult(intent, NEW_CUSTOMER_ACTIVITY_REQUEST_CODE);


            }

        });
        recyclerView.setAdapter(adapter);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

        public void onActivityResult(final int requestCode, final int resultCode, final Intent data){
            super.onActivityResult(requestCode, resultCode, data);

            if (requestCode == NEW_CUSTOMER_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
                String[] mCustomerSave = data.getStringArrayExtra(CreateCustomer.EXTRA_REPLY);
                Customer customer = new Customer(mCustomerSave[0],mCustomerSave[1],mCustomerSave[2],mCustomerSave[3]);
                mCustomerViewModel.insert(customer);
            } else {
                Toast.makeText(
                        getApplicationContext(),
                        R.string.empty_not_saved,
                        Toast.LENGTH_LONG).show();
            }
        }



}

Error message:

03-16 13:16:55.327 32615-32615/com.example.jenso.paperseller E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.jenso.paperseller, PID: 32615
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jenso.paperseller/com.example.jenso.paperseller.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.jenso.paperseller.CustomerViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.jenso.paperseller.CustomerViewModel
        at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:205)
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:133)
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:101)
        at com.example.jenso.paperseller.MainActivity.onCreate(MainActivity.java:51)
        at android.app.Activity.performCreate(Activity.java:7009)
        at android.app.Activity.performCreate(Activity.java:7000)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
        at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:197)
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:133) 
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:101) 
        at com.example.jenso.paperseller.MainActivity.onCreate(MainActivity.java:51) 
        at android.app.Activity.performCreate(Activity.java:7009) 
        at android.app.Activity.performCreate(Activity.java:7000) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 
     Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'android.arch.lifecycle.LiveData com.example.jenso.paperseller.CustomerDao.getAllCustomers()' on a null object reference
        at com.example.jenso.paperseller.CustomerRepository.<init>(CustomerRepository.java:17)
        at com.example.jenso.paperseller.CustomerViewModel.<init>(CustomerViewModel.java:20)
        at java.lang.reflect.Constructor.newInstance0(Native Method) 
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
        at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:197) 
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:133) 
        at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:101) 
        at com.example.jenso.paperseller.MainActivity.onCreate(MainActivity.java:51) 
        at android.app.Activity.performCreate(Activity.java:7009) 
        at android.app.Activity.performCreate(Activity.java:7000) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856) 
        at android.app.ActivityThread.-wrap11(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:164) 
        at android.app.ActivityThread.main(ActivityThread.java:6494) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) 

Dao:

import android.arch.lifecycle.LiveData;
        import android.arch.persistence.room.Dao;
        import android.arch.persistence.room.Delete;
        import android.arch.persistence.room.Insert;
        import android.arch.persistence.room.OnConflictStrategy;
        import android.arch.persistence.room.Query;

        import java.util.List;

@Dao
public interface CustomerDao {

    @Query("SELECT * FROM customer")
    LiveData<List<Customer>> getAllCustomers();

    @Query("SELECT * FROM customer WHERE id = :id")
    LiveData<List<Customer>> getOneCustomerById(int id);

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertAll(Customer... customer);

    @Delete
    void DeleteOneCustomer(Customer... customer);




}

Database:

import android.arch.persistence.db.SupportSQLiteDatabase;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.content.Context;
import android.os.AsyncTask;
import android.support.annotation.NonNull;


@Database(entities = {Customer.class}, version = 1,exportSchema = false)
public abstract class CustomerDatabase extends RoomDatabase {
    public abstract CustomerDao customerDao();
    private static CustomerDatabase INSTANCE;


    static CustomerDatabase getDatabase(final Context context){
        if(INSTANCE == null){
            synchronized (CustomerDatabase.class){
                if(INSTANCE == null){
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),CustomerDatabase.class,"customer_database")
                            .addCallback(sRoomDatabaseCallback)
                            .build();
                }
            }
        }
        return INSTANCE;



    }
    private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){

        @Override
        public void onOpen(@NonNull SupportSQLiteDatabase db){
            super.onOpen(db);
            new PopulateDbAsync(INSTANCE).execute();

        }
    };
    private static class PopulateDbAsync extends AsyncTask<Void, Void, Void>{
        private final CustomerDao mDao;

        PopulateDbAsync(CustomerDatabase db){
            mDao = db.customerDao();

        }
        @Override
        protected Void doInBackground(final Void... params){



            return null;



        }


    }


}

repository:

import android.app.Application;
import android.arch.lifecycle.LiveData;
import android.os.AsyncTask;

import java.util.List;

public class CustomerRepository {
    private CustomerDao mCustomerDao;
    private LiveData<List<Customer>> mAllCustomers;


    public CustomerRepository(Application application) {
            CustomerDatabase db = CustomerDatabase.getDatabase(application);

            mAllCustomers = mCustomerDao.getAllCustomers();
            mCustomerDao = db.customerDao();





    }
    LiveData<List<Customer>> getAllCustomers(){
        return mAllCustomers;

    }




    public void insert (Customer customer){
        new insertAsyncTask(mCustomerDao).execute(customer);

    }

    public void delete(Customer customer) {
        new DeleteAsyncTask(mCustomerDao).execute(customer);



    }


    private static class insertAsyncTask extends AsyncTask<Customer, Void, Void> {

        private CustomerDao mAsyncTaskDao;

        insertAsyncTask(CustomerDao dao) {
            mAsyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(final Customer... params) {
           mAsyncTaskDao.insertAll(params[0]);

            return null;
        }
    }
    private static class DeleteAsyncTask extends AsyncTask<Customer, Void, Void> {

        private CustomerDao mAsyncTaskDao;

        DeleteAsyncTask(CustomerDao dao) {
            mAsyncTaskDao = dao;
        }

        @Override
        protected Void doInBackground(final Customer... params) {
            mAsyncTaskDao.DeleteOneCustomer(params[0]);

            return null;
        }
    }


}
J.Doe2
  • 17
  • 6
  • 3
    You haven't set up your `Dao` correctly - `java.lang.NullPointerException: Attempt to invoke interface method 'android.arch.lifecycle.LiveData com.example.jenso.paperseller.CustomerDao.getAllCustomers()' on a null object reference` – PPartisan Mar 16 '18 at 13:31
  • Yeah, exactly. Looks like your `CustomerDao` is null, I guess – LS05 Mar 16 '18 at 13:32
  • added my Dao can't see any trouble – J.Doe2 Mar 16 '18 at 13:34
  • It's the instance of `CustomerDao` that is `null`, so the problem won't be within the `CustomerDao` class itself, only in a class that tries to create a `CustomerDao` instance - Can you post your `@Database` class? – Michael Dodd Mar 16 '18 at 13:45
  • And `getDatabase()` has been called in `onCreate()` before your `ViewModelProvider` tries to populate your activity? What's happening on line 51 of `MainActivity.java`? – Michael Dodd Mar 16 '18 at 13:52
  • can you give me the row – J.Doe2 Mar 16 '18 at 13:55
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zoe Mar 16 '18 at 13:57
  • I moved it below getDataCall and still gives me the error – J.Doe2 Mar 16 '18 at 14:01

0 Answers0