0

I want to create a function that gets mp3 files from the raw folder and returns a list these in mp3 in objects

data class mp3(
    val id: Int ,
    val rawResourceId : Int ,
    val title : String ,
    val isPlaying : Boolean
    )
class MP3Provider(private val context: Context) {

    fun getMp3List(): List<mp3> {
        val mp3List = mutableListOf<mp3>()
        val res = context.resources
        val rawResources = res.assets.list("raw")?.filter { it.endsWith(".mp3") }
        rawResources?.forEachIndexed { index, rawResource ->
            val rawResourceId = res.getIdentifier(rawResource, "raw", context.packageName)
            val mp3 = mp3(
                id = index,
                rawResourceId = rawResourceId,
                title = rawResource.substringBeforeLast(".mp3"),
                isPlaying = false
            )
            mp3List.add(mp3)
        }
        return mp3List
    }
}
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val provider = MP3Provider(this)
        val mp3List = provider.getMp3List()

        mp3List.forEach {
            Log.d("mp3", "Title: ${it.title}, ID: ${it.id}, Raw Resource ID: ${it.rawResourceId}, Is Playing: ${it.isPlaying}")
        }
    }
}

ran this in my MainActivity to make sure the code works but the list doesn't even fill up knowing that I added mp3s to raw folder both in debug and main

and ran the same code in my MainFragment in the OnViewcreated since i wanted to use navigation component but It didn't work neither
I've been stuck in this for two days now , I really hope that somebody help me because I'm still beginner. The reflections code

 val res = context.resources
            val fieldList = R.raw::class.java.fields
            fieldList.forEachIndexed { index, field ->
                if (field.type == Int::class.java) {
                    val fieldName = field.name
                    if (fieldName.endsWith(".mp3")) {
                        val rawResourceId = field.getInt(null)
                        val title = fieldName.substringBeforeLast(".mp3")
                        val mp3= mp3(
                            id = index,
                            rawResourceId = rawResourceId,
                            title = title,
                            isPlaying = false
                        )
                        mp3List.add(mp3)
                    }
                }
            }
            return mp3List
Rdog420
  • 1
  • 1

0 Answers0