为什么我会收到错误消息Cant实例化Class

时间:2018-03-16 13:28:02

标签: java android viewmodel

当我启动我的应用程序时,我遇到了一个巨大的错误,我的ViewHolder和我的主要活动与我的错误代码请帮助不明白为什么它给我这个错误...我也知道这个错误消息继续弹出,但如果你看不出有什么问题那么就没有办法处理它,所以我既要感谢也要抱歉。如果您需要更多代码,请告诉我,我很乐意提供帮助!: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();
            }
        }



}

错误讯息:

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) 
道:

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




}

数据库:

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;



        }


    }


}

存储库:

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


}

0 个答案:

没有答案