Reputation: 96
I started a project for making a music player.Initially i have Listed all mp3 files using ApI level 29.But i am facing the problem in creating a mediaplayer.Everytime the error is showing is "Found a null Uri"....I have tried this... fun getAppExternalFilesDir(): File? { return if (Build.VERSION.SDK_INT >= 29) { getExternalFilesDir(null) } else { // @Deprecated in API 29. // /storage/emulated/0 Environment.getExternalStorageDirectory() } }
fun ListDir(f: File) {
var files: Array<File>? = f.listFiles()
list.clear()
if (files != null) {
for (file: File in files) {
if (file.name.endsWith(".mp3")){
list.add(Model(file.name))
}
}
}
listview.setOnItemClickListener { parent:AdapterView<*>, view:View, position:Int, id:Long ->
if (position>=0) {
var textcopy: TextView = view.findViewById(R.id.foldername)
var namecopied: String = textcopy.text.toString()
mediaplayer = MediaPlayer()
var uri: Uri = Uri.parse((getAppExternalFilesDir().toString() + "/" + namecopied))
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show()
mediaplayer = MediaPlayer.create(this, uri)
mediaplayer.prepare()
mediaplayer.start()
}
//where getAppExternalFilesDir() =getExternalFilesDir(null)
}
Upvotes: 1
Views: 2560
Reputation: 8106
Your code is not optimized as well, you can use cold sequences to search through files, it'll destroy older instances of file as it runs
fun ListDir(f: File) {
val mp3Files = f.walk().map { it.absolutePath }.filter { it.endsWith(".mp3") }.toList()
listview.setOnItemClickListener { parent:AdapterView<*>, view:View, position:Int, id:Long ->
if (position>=0) {
...
var uri: Uri = Uri.fromFile(File(mp3Files[position]))
...
}
}
}
This will create proper Uri that you can pass to the media player to play the mp3 files.
Upvotes: 1