Fixed search bug

Old search code in GenreRepository.kt was very slow on large libraries.
Used selection parameters for contentResolver.query instead of fetching all genres and filtering afterwards.
Changed code in SearchRepository.kt to call new function.
This commit is contained in:
SirPotato10000 2020-11-24 20:47:49 +03:00
parent bf2f4ac757
commit 21904e2a26
2 changed files with 22 additions and 4 deletions

View file

@ -32,6 +32,8 @@ import code.name.monkey.retromusic.util.PreferenceUtil
interface GenreRepository {
fun genres(): List<Genre>
fun genres(query: String): List<Genre>
fun songs(genreId: Long): List<Song>
}
@ -44,6 +46,9 @@ class RealGenreRepository(
return getGenresFromCursor(makeGenreCursor())
}
override fun genres(query: String): List<Genre> {
return getGenresFromCursor(makeGenreCursor(arrayOf("%$query%")))
}
override fun songs(genreId: Long): List<Song> {
// The genres table only stores songs that have a genre specified,
// so we need to get songs without a genre a different way.
@ -161,4 +166,19 @@ class RealGenreRepository(
return null
}
}
private fun makeGenreCursor(selectionValues: Array<String>?): Cursor? {
val selection = MediaStore.Audio.GenresColumns.NAME + " LIKE ?"
val projection = arrayOf(Genres._ID, Genres.NAME)
return try {
contentResolver.query(
Genres.EXTERNAL_CONTENT_URI,
projection,
selection,
selectionValues,
PreferenceUtil.genreSortOrder
)
} catch (e: SecurityException) {
return null
}
}
}

View file

@ -45,10 +45,8 @@ class RealSearchRepository(
results.add(context.resources.getString(R.string.albums))
results.addAll(albums)
}
val genres: List<Genre> = genreRepository.genres().filter { genre ->
genre.name.toLowerCase(Locale.getDefault())
.contains(searchString.toLowerCase(Locale.getDefault()))
}
val genres = genreRepository.genres(searchString)
if (genres.isNotEmpty()) {
results.add(context.resources.getString(R.string.genres))
results.addAll(genres)