Reputation: 129
Following the example given by android, I extended the ViewModel class
public class NameViewModel extends ViewModel {
private MutableLiveData<String> currentName;
public MutableLiveData<String> getCurrentName() {
if (currentName == null) {
currentName = new MutableLiveData<String>();
}
return currentName;
}}
and i observed the LiveData objects
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);
}}
and my dependencies in build.gradle are
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'
}
Running this code is giving Cannot create an instance of class NameViewModel, what am I doing wrong in here?
Upvotes: 0
Views: 620
Reputation: 1
Instead:
model = new ViewModelProvider(this).get(NameViewModel.class);
Try this:
model = new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NameViewModel.class);
Upvotes: 0
Reputation: 26
You are missing the constructor in the ViewModel class, so add public NameViewModel() {};
to your ViewModel.
Upvotes: 1
Reputation: 129
I had NameViewModel in the same java file as NameActivity, where it should be in separate file NameViewModel.java, this fixed it.
Upvotes: 0
Reputation: 8477
Should you, perhaps, add an empty constructor in the ViewModel
an call super()
there?
Upvotes: 0
Reputation: 51
Nothing seems to be wrong with the code though.
Could you check if you have this particular dependency version in your build.gradle
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
and could you please add your build.gradle .
Upvotes: 0