I'm recently learning about the architectural components and was following the old tutorial where they used the old method:
mainActivityViewModel =
new ViewModelProvider(this).get(MainActivityViewModel.class);
But in the documentation for the ViewModelProvider, the only constructors available are
ViewModelProvider(ViewModelStoreOwner, Factory) &
ViewModelProvider(ViewModelStore, Factory).
So I did something like this but I'm not sure what to do in the overridden method and it currently returns null that crashes the program.
public class MainActivity extends AppCompatActivity {
private NoteViewModel noteViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel = new ViewModelProvider(this, new ViewModelProvider.Factory() {
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return null;
}
}).get(NoteViewModel.class);
noteViewModel.getAllNotes().observe(this, new Observer<List<NoteEntity>>() {
@Override
public void onChanged(List<NoteEntity> noteEntities) {
Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
}
});
}
}
Is my approach correct? I'm absolutely lost right now. What am I supposed to return from the overridden method?
Use this
noteViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(NoteViewModel.class;
We use custom factory, when we pass param to the constructor of ViewModel (apart from Application param).
and gradle dependency in case,
def lifecycle_version = "2.2.0"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
//
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
First you need to initialize viewmodel in activity class like :
noteViewModel = ViewModelProvider(this).get(NoteViewModel.class);
In NoteViewModel.java
You need to define livedata variable for storing updated data provided by model and update post to view model
NoteViewModel.java file look like :
public class NoteViewModel extends AndroidViewModel {
AppRepository appRepository;
MediatorLiveData<List<NoteEntity>> mediatorData;
public NoteViewModel (@NonNull Application application) {
super(application);
mediatorData=new MediatorLiveData<>();
appRepository=new AppRepository((MyApplication).apiService, application.retrofit);
}
public MediatorLiveData<List<NoteEntity>> getMediatorLiveData() {
return mediatorVideoData;
}
public void getNoteEntry()
{
try {
mediatorData.addSource(appRepository.getNoteEntry(), new Observer<List<NoteEntity>>() {
@Override
public void onChanged(@Nullable List<NoteEntity> data) {
mediatorData.postValue(data);
}
});
}catch (Exception e)
{
}
}
}
In onCreate() of Mainactivity register observer like and call the API from view model like
noteViewModel.getMediatorLiveData().observe(this, new Observer<List<NoteEntity>>() {
@Override
public void onChanged(List<NoteEntity> noteEntities) {
Toast.makeText(MainActivity.this,"Changed",Toast.LENGTH_LONG).show();
}
});
noteViewModel.getNoteEntry();
AppRepository.java file look like
class AppRepository() {
ApiService apiService;
Retrofit retrofit;
public AppRepository(ApiService apiService ,Retrofit retrofit){
this.apiService = apiService;
this.retrofit = retrofit;
}
public MediatorLiveData<List<NoteEntity>> getNotes() {
MediatorLiveData<List<NoteEntity>> data = new MediatorLiveData<List<NoteEntity>>()
apiService.getNotes()
.enqueue(new Callback<List<NoteEntity>> {
@Override
void onResponse(
Call<List<NoteEntity>> call,
Response<List<NoteEntity>> response
) {
if (response.isSuccessful()) {
if(response.body()!=null){
data.postValue(response.body()); //successfull data
}else{
data.postValue(null); //error
}
} else {
data.postValue(null); //error
}
}
@Override
fun onFailure(
Call<List<NoteEntity>> call,
Throwable t
) {
data.postValue(null); //error
}
})
return data;
}
}
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