本文介绍了无法创建类 ViewModel 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 Android 架构组件编写一个示例应用程序,但即使尝试了几天,我也无法让它工作.它给了我上述例外.
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.
生命周期所有者:-
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());
}
}
});
}
}
视图模型:-
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;
}
}
推荐答案
如果您使用的是 Hilt
,请确保您的 Activity/Fragment 具有 @AndroidEntryPoint
注释
if you are using Hilt
, ensure your activity/fragment is having @AndroidEntryPoint
annotation
这篇关于无法创建类 ViewModel 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!