Unable to instantiate ViewModel class

I am trying to write an example application using the components of the Android architecture, but even after several days of work, I could not get it to work. This gives me the above exception.

Life Cycle Owner: -

public class MainActivity extends LifecycleActivity {

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView = findViewById(R.id.tv_user);
        PostViewModel viewModel = ViewModelProviders.of(this).get(PostViewModel.class);
        viewModel.loadPosts();
        viewModel.getPost().observe(this, new Observer<Post>() {
            @Override
            public void onChanged(@Nullable Post post) {
                if(post != null) {
                    textView.setText(post.toString());
                }
            }
        });
    }
}

ViewModel: -

public class PostViewModel extends ViewModel {
    private MediatorLiveData<Post> post;
    private PostRepository postRepo;

    PostViewModel() {
        post = new MediatorLiveData<>();
        postRepo = new PostRepository();
    }

    public LiveData<Post> loadPosts() {
        post.addSource(postRepo.getPost(),
                post -> this.post.setValue(post)
        );
        return post;
    }

    @NonNull
    public LiveData<Post> getPost() {
        return post;
    }
}
+34
source share
15 answers

Create your own constructor public.

+67
source

Make sure yours ViewModelhas a constructor with only one parameter, i.e. c Application.

example:

public YourViewModel(Application application) {
    super(application);
    ...
+12
source

Kotlin annotationProcessor build.gradle kapt.

:

annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"

apply plugin: 'kotlin-kapt' buidl.gradle.

Kotlin

+8

, , . Android Developer . , - .

i.e.,

public PostViewModel() {}

+4

, .

+3

, . ..

  1. ,
  2. ,

  3. , gridle , , .

  4. . viewModel
+2
  1. , Solution , .
  2. , Logcat, .
+2

viewmodel , , "DaggerAppCompatActivity"

public class UserComments extends AppCompatActivity 

public class UserComments extends DaggerAppCompatActivity
+2

AndroidX.

androidx.lifecycle:lifecycle-viewmodel:2.0.0-beta01 androidx.lifecycle:lifecycle-viewmodel:2.0.0-beta01 Proguard .

https://issuetracker.google.com/issues/112230489

2.0.0, Proguard, .

:

java.lang.RuntimeException: Cannot create an instance of class my.custom.viewmodel.CustomViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:202)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
......
Caused by: java.lang.NoSuchMethodException: <init> [class android.app.Application]
at java.lang.Class.getConstructor0(Class.java:2204)
at java.lang.Class.getConstructor(Class.java:1683)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
... 34 more


  androidx.test.espresso.PerformException: Error performing 'single click - At Coordinates: 539, 1167 and precision: 16, 16' on view 'with id: my.test:id/button_return_to_main_menu'.
at androidx.test.espresso.PerformException$Builder.build(PerformException.java:82)
at androidx.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:79)
.....
Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{my.custom.domain.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class my.custom.viewmodel.CustomViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
+1

AndroidViewModel ViewModel.

public class YourViewModel extends AndroidViewModel {

    public YourViewModel(Application application) {
        super(application);

        //Todo: ...
    }

}
+1

PostViewModel , ,

+1

.

0

Android-arcuitecture-component BasicSample, , .

AndroidManifest.xml

, , aplicacion de BasicApp, .

...
<application
    android:name=".BasicApp"
    android:allowBackup="false"
0

ListItemViewModelFactory .

0

Creating an additional constructor that was empty without parameters and publicly available solved the problem.

0
source

Source: https://habr.com/ru/post/1681061/


All Articles