I have a bunch of models in my app, which are data classes. Through my app (which is a media player) I follow pretty much the same routine for getting instances of these classes.I want to query the database(which here is the MediaStore) using a projection for Songs/Albums/Artists, and I want to create instances and append those in a list, which will serve as my library.
What I have done so far in order to create a list of Songs is as followed:
val SONG_SEARCH_PROJ = hashMapOf<String, String>(
"id" to MediaStore.Audio.AudioColumns._ID,
"title" to MediaStore.Audio.AudioColumns.TITLE,
"album" to MediaStore.Audio.AudioColumns.ALBUM,
"album id" to MediaStore.Audio.AudioColumns.ALBUM_ID,
"artist" to MediaStore.Audio.AudioColumns.ARTIST,
"artist id" to MediaStore.Audio.AudioColumns.ARTIST_ID,
"data" to MediaStore.Audio.AudioColumns.DATA)
var songLibrary: () -> ArrayList<SongModel> = {
var songsList = ArrayList<SongModel>()
val cursor = context.contentResolver.query(
uri,
SONG_SEARCH_PROJ.values.toTypedArray(), selection, null, sortOrder
)
cursor?.let { current_cursor ->
while (!current_cursor.isAfterLast) {
SONG_SEARCH_PROJ.apply {
songsList.add(
SongModel(
current_cursor.getData("id", this).toInt(),
current_cursor.getData("title", this),
current_cursor.getData("data", this),
current_cursor.getData("artist", this),
current_cursor.getData("album", this),
null
)
)
}
current_cursor.moveToNext()
}
cursor.close()
}
songsList
}
Also for better readability, I have created an extension function for the Cursor
class, which gets a hashmap, and a string which will serve as the key.
fun Cursor.getData(key: String, hashmap: HashMap<String, String>): String{
return this.getString(this.getColumnIndex(hashmap[key]))
}
My data classes are also as followed:
@Entity
data class SongModel(
@PrimaryKey val id: Int,
val name: String,
val Location: String,
val ArtistName: String,
val AlbumName: String,
val ArtWorkLocation:String?)
======
data class AlbumModel(@PrimaryKey val name: String, val artistName: String, val songList: ArrayList<SongModel>)
======
data class ArtistModel(@PrimaryKey val Name: String, var albumList: ArrayList<AlbumModel>)
=====
My problem is at the moment, I can't generify the "createLibraryOf_X_Model" function, since Kotlin does not accept creating instance of generic types. I have also stumbled upon factory pattern, but I had a hard time adjusting it to my current problem.
Aucun commentaire:
Enregistrer un commentaire