简体   繁体   English

Kotlin 中的音乐 URI 空指针异常

[英]Music URI null pointer exception in Kotlin

Greeting all I had been passed over several days over and still can't solve the problem, null pointer问候我都过了好几天了还是解决不了问题,空指针

exception error on setting music URI "var musicTrack = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,curSong!!)"设置音乐 URI 时出现异常错误“var musicTrack = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,curSong!!)”

enter image description here在此处输入图片说明

 fun PlaySong(){
    mp!!.reset()
    var song = songlist?.get(songPosition!!)
    var curSong = song?.Id


    var musicTrack = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,curSong!!)
    try {
        mp!!.setDataSource(applicationContext,musicTrack!!)
    }catch (e: Exception){
        Log.e("Music Service","Error On Setting Data Source",e)
    }
    mp!!.prepareAsync()
}

The stack trace is saying it's line 78 where the problem is happening.堆栈跟踪表明问题发生在第 78 行。 mp is probably null and you're trying to call a method on it, at a guess. mp可能为空,并且您正在尝试对其调用一个方法,猜测。

Using !!使用!! is a bad sign because it means that value could be null, but you're not handling that possibility and saying "trust me, it's never going to be null".是一个不好的信号,因为这意味着 value 可能为 null,但您没有处理这种可能性并说“相信我,它永远不会为 null”。 That usually doesn't work out!那通常是行不通的! I know this from experience...我从经验得到的这个结论...

Either make mp a non-nullable type if you know it's never going to be null, otherwise you need to null-check it before you do anything with it.如果您知道它永远不会为空,要么将mp设为不可为空的类型,否则您需要在对它执行任何操作之前对其进行空检查。 Never use !!千万不要用!! (the rare times you actually do need it, you'll know you need it and it's an exception to the rule) (极少数情况下你确实需要它,你会知道你需要它,这是规则的一个例外)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM