I load my data using an AsyncTask
in my ViewModel
but when i try to observe the data inside my fragment then i get the exception:
Caused by: java.lang.ClassCastException: MainFragment cannot be cast to android.arch.lifecycle.LifecycleOwner
This is my ViewModel:
private MutableLiveData<ArrayList<Song>> songs;
public LiveData<ArrayList<Song>> getSongs() {
if (songs == null) {
songs = new MutableLiveData<ArrayList<Song>>();
loadSongs();
}
return songs;
}
@SuppressLint("StaticFieldLeak")
private void loadSongs() {
new AsyncTask<Void, Void, ArrayList<Song>>() {
@Override
protected ArrayList<Song> doInBackground(Void... voids) {
ArrayList<Song> data = new ArrayList<>();
//Add songs (collapsed)
return data;
}
@Override
protected void onPostExecute(ArrayList<Song> data) {
songs.postValue(data);
}
}.execute();
}
And this is my fragment where i want my data inside my listview:
viewModel = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
//TODO: Fix this!
viewModel.getSongs().observe((LifecycleOwner) this, new Observer<ArrayList<Song>>() {
@Override
public void onChanged(@Nullable ArrayList<Song> songs) {
adapter = new ListViewAdapter(R.layout.songlist_customlayout, viewModel.getSongs().getValue(), getActivity());
}
});
What is the problem here?
I fixed the ClassCastException
by migrating my project to androidx
.
Now i dont get the error anymore :)