无法打开活动:无法创建android视图模型的示例

ee7vknir  于 2021-07-06  发布在  Java
关注(0)|答案(3)|浏览(416)

我正在创建一个应用程序来扫描条形码,并使用android视图模型和livedata将这些信息导入房间数据库。这是错误信息

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) 

这是androidviewmodel类

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

}

下面是类/活动datadisplay,它有一个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();
        }
    }

}

这个问题类似于另一个问题,但我在teamviewmodel的构造函数中只有一个参数。
其余的代码在github上
谢谢您

zsohkypk

zsohkypk1#

这个问题可能来自其他部分,如存储库或房间
我只是更新依赖项
def室版本=“2.2.5”

implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
pcww981p

pcww981p2#

简单类型

ViewModelProvider(
        this@RecipeListActivity,
        ViewModelProvider.AndroidViewModelFactory(this.application)
    ).get(RecipeListViewModel::class.java)
m1m5dgzv

m1m5dgzv3#

您的viewmodel需要有一个factory类。

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

在示例化视图模型时,您可以这样做:

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

原始答案

相关问题