[英]Android LiveData, Cannot create an instance of class viewModel
按照android给出的示例,我扩展了 ViewModel class
public class NameViewModel extends ViewModel {
private MutableLiveData<String> currentName;
public MutableLiveData<String> getCurrentName() {
if (currentName == null) {
currentName = new MutableLiveData<String>();
}
return currentName;
}}
我观察了 LiveData 对象
public class NameActivity extends AppCompatActivity {
private NameViewModel model;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Other code to setup the activity...
// Get the ViewModel.
model = new ViewModelProvider(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = new Observer<String>() {
@Override
public void onChanged(@Nullable final String newName) {
// Update the UI, in this case, a TextView.
nameTextView.setText(newName);
}
};
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
model.getCurrentName().observe(this, nameObserver);
}}
我在 build.gradle 中的依赖项是
dependencies {
def lifecycle_version = "2.2.0"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
运行此代码给出无法创建 class NameViewModel 的实例,我在这里做错了什么?
您缺少 ViewModel class 中的构造函数,因此添加public NameViewModel() {};
到您的 ViewModel。
不过,代码似乎没有任何问题。
你能检查一下你的 build.gradle 中是否有这个特定的依赖版本吗
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
您能否添加您的 build.gradle。
您是否应该在ViewModel
中添加一个空的构造函数并在那里调用super()
?
我在同一个 java 文件中有 NameViewModel 作为 NameActivity,它应该在单独的文件 NameViewModel.java 中,这修复了它。
而是: model = new ViewModelProvider(this).get(NameViewModel.class);
试试这个: model = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NameViewModel.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.