无法在安卓中创建 ViewModel 实例

huangapple go评论113阅读模式
英文:

Cannot create instance of ViewModel in android

问题

以下是翻译好的内容:

你好,我是Android的新手,一直在尝试学习MVVM,但是我无法弄清楚为什么会出现错误,显示无法创建ViewModel类的实例:

以下是我收到的错误信息:

2020-06-29 12:30:26.293 15174-15174/com.carrot.roomdatabase E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.roomdatabase, PID: 15174
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.roomdatabase/com.carrot.roomdatabase.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.carrot.roomdatabase.ViewModel
    ...
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.carrot.roomdatabase.ViewModel
    ...
     Caused by: java.lang.InstantiationException: java.lang.Class<com.carrot.roomdatabase.ViewModel> has no zero argument constructor
    ...

以下是我的类:

MainActivity.java类:

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private recycleViewAdapter adapter;
    private ViewModel viewModel;
    private List<NotesEntity> notesEntityList = new ArrayList<>();
    private FloatingActionButton btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(ViewModel.class);
        viewModel.getAllNotes().observe(this, new Observer<List<NotesEntity>>() {
            @Override
            public void onChanged(List<NotesEntity> notesEntities) {
                Toast.makeText(MainActivity.this, "onChanged", Toast.LENGTH_SHORT).show();
                adapter.notifyDataSetChanged();
            }
        });

        btn = findViewById(R.id.floatingActionButton);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this , AddNote.class));
            }
        });
        init();
    }
    private void init(){
        adapter = new recycleViewAdapter(notesEntityList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

ViewModel.java类:

public class ViewModel extends AndroidViewModel {
    private Repository repository;
    private LiveData<List<NotesEntity>> allNotes;
    public ViewModel(@NonNull Application application) {
        super(application);
        repository = new Repository(application);
        allNotes = repository.getNotes();
    }

    public void insertThis(NotesEntity notesEntity){
        repository.Insert(notesEntity);
    }
    public void deleteThis(NotesEntity notesEntity){
        repository.Delete(notesEntity);
    }

    public LiveData<List<NotesEntity>> getAllNotes(){
        return allNotes;
    }
}

有人能帮助我找出我做错了什么吗?谢谢。

英文:

Hello I am new to android and have been trying to learn MVVM but I am not able to figure out why I am error saying cannot create instance of viewmodel class :

These are the errors that I am getting:

2020-06-29 12:30:26.293 15174-15174/com.carrot.roomdatabase E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.carrot.roomdatabase, PID: 15174
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.carrot.roomdatabase/com.carrot.roomdatabase.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.carrot.roomdatabase.ViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3388)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3527)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        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:2123)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7710)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.carrot.roomdatabase.ViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.carrot.roomdatabase.MainActivity.onCreate(MainActivity.java:31)
        at android.app.Activity.performCreate(Activity.java:7820)
        at android.app.Activity.performCreate(Activity.java:7809)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3363)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3527)&#160;
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)&#160;
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)&#160;
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:107)&#160;
        at android.os.Looper.loop(Looper.java:214)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7710)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)&#160;
     Caused by: java.lang.InstantiationException: java.lang.Class&lt;com.carrot.roomdatabase.ViewModel&gt; has no zero argument constructor
        at java.lang.Class.newInstance(Native Method)
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)&#160;
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)&#160;
        at com.carrot.roomdatabase.MainActivity.onCreate(MainActivity.java:31)&#160;
        at android.app.Activity.performCreate(Activity.java:7820)&#160;
        at android.app.Activity.performCreate(Activity.java:7809)&#160;
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1318)&#160;
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3363)&#160;
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3527)&#160;
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)&#160;
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)&#160;
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)&#160;
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)&#160;
        at android.os.Handler.dispatchMessage(Handler.java:107)&#160;
        at android.os.Looper.loop(Looper.java:214)&#160;
        at android.app.ActivityThread.main(ActivityThread.java:7710)&#160;
        at java.lang.reflect.Method.invoke(Native Method)&#160;
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)&#160;
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)&#160;
2020-06-29 12:30:26.304 15174-15174/? I/Process: Sending signal. PID: 15174 SIG: 9

Below are my classes

MainActivity.java class:


public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private recycleViewAdapter adapter;
    private ViewModel viewModel;
    private List&lt;NotesEntity&gt; notesEntityList = new ArrayList&lt;&gt;();
    private FloatingActionButton btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(ViewModel.class);
        viewModel.getAllNotes().observe(this, new Observer&lt;List&lt;NotesEntity&gt;&gt;() {
            @Override
            public void onChanged(List&lt;NotesEntity&gt; notesEntities) {
                Toast.makeText(MainActivity.this, &quot;onChanged&quot;, Toast.LENGTH_SHORT).show();
                adapter.notifyDataSetChanged();
            }
        });

        btn = findViewById(R.id.floatingActionButton);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this , AddNote.class));
            }
        });
        init();
    }
    private void init(){
        adapter = new recycleViewAdapter(notesEntityList);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

ViewModel.java class:

public class ViewModel extends AndroidViewModel {
    private Repository repository;
    private LiveData&lt;List&lt;NotesEntity&gt;&gt; allNotes;
    public ViewModel(@NonNull Application application) {
        super(application);
        repository = new Repository(application);
        allNotes = repository.getNotes();
    }

    public void insertThis(NotesEntity notesEntity){
        repository.Insert(notesEntity);
    }
    public void deleteThis(NotesEntity notesEntity){
        repository.Delete(notesEntity);
    }

    public LiveData&lt;List&lt;NotesEntity&gt;&gt; getAllNotes(){
        return allNotes;
    }
}

can someone please help me in figuring out what is it that I am doing wrong.
Thank you.

答案1

得分: 3

初始化 ViewModel 的代码如下。您还需要在 ViewModelProvider 构造函数中传递 ViewModelFactory。

viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(ViewModel.class);

希望这对您有所帮助......

英文:

Initialise ViewModel like this. You need to also pass ViewModelFactory with ViewModelProvider constructor.

viewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(ViewModel.class);

Hope this helps.......

huangapple
  • 本文由 发表于 2020年6月29日 15:09:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/62632926.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定