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; } }
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.
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.
Make your constructor public
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With