Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an instance of class ViewModel

I am trying to write a sample app using Android architecture components and but even after trying for days I could not get it to work. It gives me the above exception.

Lifecycle 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;     } } 
like image 501
Parag Kadam Avatar asked Jul 09 '17 15:07

Parag Kadam


People also ask

What is AndroidViewModel?

The AndroidViewModel class is a subclass of ViewModel and similar to them, they are designed to store and manage UI-related data are responsible to prepare & provide data for UI and automatically allow data to survive configuration change.

What is the use of ViewModel class?

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.


1 Answers

Make your constructor public.

like image 149
CommonsWare Avatar answered Sep 30 '22 03:09

CommonsWare