I have a music list obtained from:
MusicDatabase.kt
override fun getContentProviderValue(): MutableList<Songs> {
val songList = mutableListOf<Songs>()
val collection = sdk29AndUp {
MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
} ?: MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
//Get songs from provider
context.contentResolver.query(
collection,
projection,
selection,
null,
PreferenceHelper.storeAllSongsSortOrder //Sort order.
).use { cursor ->
............
}
}
Using SharedPreference, I am storing and obtaining sort order like this:
PreferenceHelper.kt
//store allSongs sort order
var storeAllSongsSortOrder: String?
get() = preferences.getString(allSongSortOrder.first, allSongSortOrder.second)
set(value) = preferences.edit {
if (value != null) {
it.putString(allSongSortOrder.first, value)
}
}
I obtain the songList like this:
SongsFragment.kt
mainViewModel.mediaItems.observe(viewLifecycleOwner){ result->
when(result.status) {
Status.SUCCESS -> {
result.data?.let { songs ->
allSongsAdapter.songs = songs
........
}
In my songs fragment, when user clicks "Sort", a dropdown will appear with 2 options:
- Sort by name
- Sort by date
When user clicks sort by name, I do this:
SongsFragment.kt
PreferenceHelper.storeAllSongsSortOrder = Constants.SORT_TITLE
binding.rcvAllSongs.invalidate()
allSongsAdapter.notifyDataSetChanged()
When user clicks sort by date, I do this:
PreferenceHelper.storeAllSongsSortOrder = Constants.SORT_LAST_ADDED
binding.rcvAllSongs.invalidate()
allSongsAdapter.notifyDataSetChanged()
PROBLEM: The list is not updating real time as I select, I have to close the app and open before my list gets the selected sort order.
I want – when I click e.g "Sort by date" – The list should update immediately and display songs based on date added.
2
Answers
You are not assigning the updated list to allSongsAdapter after user presses a button.
So either you make sure that
mainViewModel.mediaItems.observe
is invoked when user selects sort, which is only possible if MusicTable is updated or you save the list received inmainViewModel.mediaItems.observe
in a variable and then sort and reassign it when user wants to sort the listYou can propably do something like this: