Unable to open activity: cannot create instance of Android View Model

非 Y 不嫁゛ 提交于 2019-12-11 17:31:58

问题


I am creating an app to scan a barcode and get that information into a Room Database using Android View Model and LiveData. Here is the error message

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.davin.scoutingapp2019/com.example.davin.scoutingapp2019.DataDisplay}: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6123)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
 Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.davin.scoutingapp2019.TeamViewModel
    at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:207)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102)
    at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30)
    at android.app.Activity.performCreate(Activity.java:6672)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6123) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Constructor.newInstance0(Native Method)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:430)
    at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199)
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) 
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) 
    at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30) 
    at android.app.Activity.performCreate(Activity.java:6672) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6123) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.example.davin.scoutingapp2019.TeamDAO com.example.davin.scoutingapp2019.TeamsDatabase.teamDAO()' on a null object reference
    at com.example.davin.scoutingapp2019.TeamRepository.<init>(TeamRepository.java:15)
    at com.example.davin.scoutingapp2019.TeamViewModel.<init>(TeamViewModel.java:15)
    at java.lang.reflect.Constructor.newInstance0(Native Method) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:430) 
    at android.arch.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:199) 
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:134) 
    at android.arch.lifecycle.ViewModelProvider.get(ViewModelProvider.java:102) 
    at com.example.davin.scoutingapp2019.DataDisplay.onCreate(DataDisplay.java:30) 
    at android.app.Activity.performCreate(Activity.java:6672) 
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2612) 
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2724) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6123) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757) 

This is the AndroidViewModel class

package com.example.davin.scoutingapp2019;

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

import java.util.List;

public class TeamViewModel extends AndroidViewModel {
    private TeamRepository mRepository;
    private LiveData<List<Team>> mAllData;

    public TeamViewModel(Application application) {
        super(application);
        mRepository = new TeamRepository(application);
        mAllData = mRepository.getAllWords();
    }


    public LiveData<List<Team>> getAllTeams() {
        return mAllData;
    }

    public void insert(Team team) {
        mRepository.insert(team);
    }


}

Here is the class/activity DataDisplay which has an instance of TeamViewModel

package com.example.davin.scoutingapp2019;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import java.util.List;

public class DataDisplay extends AppCompatActivity {


    private TeamViewModel teamViewModel;
    public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_display);
        RecyclerView recyclerView = findViewById(R.id.recyclerview);
        final TeamListAdapter adapter = new TeamListAdapter(this);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        teamViewModel = ViewModelProviders.of(this).get(TeamViewModel.class);
        teamViewModel.getAllTeams().observe(this, new Observer<List<Team>>() {
            @Override
            public void onChanged(@Nullable final List<Team> teams) {
                // Update the cached copy of the words in the adapter.
                adapter.setTeams(teams);
            }
        });
    }




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

        if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            Destring destring=new Destring(data.getStringExtra("str"));
            Team newTeam= new Team(destring.getTeamNumber(),destring.getPosition(),destring.getSandstorm("hab line"),destring.getSandstorm("cargo balls"),destring.getSandstorm("cargo hatches"),destring.getSandstorm("rocket balls"),destring.getSandstorm("rocket hatches"),destring.getTeleop("cargo balls"),destring.getTeleop("cargo hatches"),destring.getTeleop("rocket balls"),destring.getTeleop("rocket hatches"),destring.getRocketRole(),destring.getClimberRole(),destring.getOverallRole(),destring.getOtherComments());

            teamViewModel.insert(newTeam);
        } else {
            Toast.makeText(
                    getApplicationContext(),
                    R.string.empty_not_saved,
                    Toast.LENGTH_LONG).show();
        }
    }






}

This question is similar to another question but I only have one parameter in my constructor for TeamViewModel.

The rest of the code is on github

Thank You


回答1:


You need to have a factory class for your ViewModel.

public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application mApplication;
private String mParam;


public MyViewModelFactory(Application application, String param) {
    mApplication = application;
    mParam = param;
}


@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    return (T) new MyViewModel(mApplication, mParam);
}

And when instantiating the view model, you do like this:

MyViewModel myViewModel = ViewModelProviders.of(this, new MyViewModelFactory(this.getApplication(), "my awesome param")).get(MyViewModel.class);

orginal answer



来源:https://stackoverflow.com/questions/54677426/unable-to-open-activity-cannot-create-instance-of-android-view-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!