无法在类viewmodel内创建示例错误-java

2jcobegt  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(424)

我想显示notedao中favcount的总和,所以我在livedata和viewmodel中这样做

@Dao
public interface NoteDao {

    @Query("SELECT * FROM notes ORDER BY id DESC")
    List<Note> getAllNotes();

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertNote(Note note);

    @Delete
    void deleteNote(Note note);

    @Query("SELECT SUM(fav_count) as favSum FROM notes")
    LiveData<String> getFavSum();

}

这是我的实体“笔记”有fav\u计数

@Entity(tableName = "notes")

 @ColumnInfo(name = "fav_count")

 private String favCount;
 public Note() {}
 public String getFavCount() { return favCount; }
 public void setFavCount(String favCount) { this.favCount = favCount;}

这是我的存储库

public class totalRepository {

   NoteDao noteDao;

    public LiveData<String> getTotal() {
        return noteDao.getFavSum();
    }
}

这是我的viewmodel

public class NoteViewModel extends ViewModel {
    public final totalRepository repository;

    public LiveData<String> getmTotal(){
        return repository.getTotal();
    }

    public NoteViewModel(totalRepository repository) {
        this.repository = repository;
    }
}

这是我要显示数据的活动

public class Statistics extends AppCompatActivity {

    TextView syukrsum;
    String favSum = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics);
       NoteViewModel noteViewModel;
        syukrsum = findViewById(R.id.syukrSum);
        noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);
        noteViewModel.getmTotal().observe(Statistics.this, new Observer<String>() {
            @Override
            public void onChanged(String string) {
                if (string == null) {
                    favSum = "0";
                    syukrsum.setText(0);
                } else {
                    favSum = string;
                    syukrsum.setText(string);
                }

            }
        });
        }
    }

当我打开“统计”活动时,我的应用程序崩溃并出现以下错误:

2020-12-04 14:40:01.630 26822-26822/com.rhlab.syukr5 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.rhlab.syukr5, PID: 26822
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rhlab.syukr5/com.rhlab.syukr5.Activities.Statistics}: java.lang.RuntimeException: Cannot create an instance of class com.rhlab.syukr5.NoteViewModel
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3170)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3307)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2036)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:224)
        at android.app.ActivityThread.main(ActivityThread.java:7081)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928)
     Caused by: java.lang.RuntimeException: Cannot create an instance of class com.rhlab.syukr5.NoteViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:278)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185)
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)
        at com.rhlab.syukr5.Activities.Statistics.onCreate(**Statistics.java:31**)
        at android.app.Activity.performCreate(Activity.java:7258)
        at android.app.Activity.performCreate(Activity.java:7249)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3150)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3307) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2036) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:224) 
        at android.app.ActivityThread.main(ActivityThread.java:7081) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928) 
     Caused by: java.lang.InstantiationException: java.lang.Class<com.rhlab.syukr5.NoteViewModel> 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$AndroidViewModelFactory.create(ViewModelProvider.java:278) 
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.java:106) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:185) 
        at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) 
      **at com.rhlab.syukr5.Activities.Statistics.onCreate(Statistics.java:31)** 
        at android.app.Activity.performCreate(Activity.java:7258) 
        at android.app.Activity.performCreate(Activity.java:7249) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3150) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3307) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:113) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:71) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2036) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:224) 
        at android.app.ActivityThread.main(ActivityThread.java:7081) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:604) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:928) 

错误出现在statistics.java第31行

noteViewModel = new ViewModelProvider(this).get(NoteViewModel.class);

问题是:我犯了什么错?对不起,如果我的问题不清楚,请记住,我是一个新手,可能我做了巨大或愚蠢的错误,请与我忍受,并请解释解决办法!

zazmityj

zazmityj1#

它正在崩溃,因为它无法创建viewmodel的示例。为什么?
因为默认情况下,它只创建viewmodel的示例,如果它有zeo构造函数参数的话。但是viewmodel有一个构造函数参数。
您的noteviewmodel需要totalrepository示例作为构造函数参数,而您并没有告诉它从何处获取。
因此,解决方案是创建viewmodelfactory。
下面是示例代码:

import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

public class NoteViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    private final TotalRepository totalRepository;

    public NoteViewModelFactory(TotalRepository totalRepository) {
        this.totalRepository = totalRepository;
    }

    @Override
    public <T extends ViewModel> T create(Class<T> modelClass) {
        return (T) new NoteViewModel(totalRepository);
    }
}

从片段中,您需要创建viewmodel,如下所示:

NoteDao noteDao = // Initialize your NoteDao object and pass it to Total Repository
    TotalRepository totalRepository = new TotalRepository(noteDao);
    NoteViewModelFactory noteViewModelFactory = new NoteViewModelFactory(totalRepository);
    NoteViewModel noteViewModel = ViewModelProviders.of(this, noteViewModelFactory).get(NoteViewModel.class);

相关问题