I am trying to get a list of songs that matches a list of media Id's using content Resolver.
I have followed this answer Here to query items dynamically with content resolver
I am trying to query a list of songs that matches a list of id's passed.
E.G
SELECT FROM MUSIC DATABASE WHERE _ID = {12, 13, 14, 15, 16} -<< This is dynamic, not fixed. could be empty or could be more.
So, I want this to return a list of song attributes with those id.
MusicDatabase
fun getSongsInPlaylist(songIds: List<Long>): List<Songs> {
val selection = MediaStore.Audio.Media._ID + " IN (" + TextUtils.join(
",", Collections.nCopies(songIds.size, "?"))+")"
val songList = mutableListOf<Songs>()
val collection = Utility.sdk29AndUp {
MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
} ?: MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
for (i in songIds.indices) selectionArgs!![i] = songIds[i]
//Get songs from provider
context.contentResolver.query(
collection,
projection,
selection,
arrayOf(selectionArgs.toString()),
MediaStore.Audio.Media.DEFAULT_SORT_ORDER //Sort in alphabetical order based on display name.
).use { cursor ->
if (cursor?.moveToFirst() == true) {
do {
}
MusicViewModel
fun doGetAllSongsInPlaylist(songIds: List<Long>){
val permissionGranted = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
if (permissionGranted){
viewModelScope.launch {
val songs = songsInPlaylistDatabase.getSongsInPlaylist(songIds)
_songsInPlaylist.value = Resource.success(songs)
}
}
}
Fragment
args.playlist.playlistId?.let { roomPlaylistViewModel.doGetAllSongsInPlaylist(it) }
roomPlaylistViewModel.songsInPlaylist.observe(viewLifecycleOwner){ songs->
for (songId in songs){
songId.songId.let { it1 ->
if (it1 != null) {
songIdArray.add(it1)....//I am getting songId's and saving in an array
}
}
}
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
playlistViewModel.doGetAllSongsInPlaylist(songIdArray)...//I am passing the song Id's stored in array here
playlistViewModel.songsInPlaylist.collect{ result ->
when(result.status) {
Status.SUCCESS -> {
result.data?.let { songs ->
Log.e("lisx", songs.toString())
}
}
Status.ERROR -> Unit
Status.LOADING -> Unit
}
}
}
I am getting an error:
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters