我正在创建一个音乐播放器应用程序,我会提取活动中的所有歌曲,当您单击该活动时,它将把歌曲传递给播放器活动,但是只要我单击列表中的项目,该应用程序就会崩溃,导致媒体播放器一片空白 这是我的代码
//opening player acitivity from adapter
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.songname.text = songsList[position].title
holder.itemView.setOnClickListener {
val i = Intent(context, PlayerActivity::class.java)
i.putExtra("position", position)
context.startActivity(i)
}
这是我的PlayerActivity的代码
class PlayerActivity: AppCompatActivity() {
private var position: Int = 0
lateinit var songlist: List<MusicModel>
lateinit var uri: Uri
lateinit var mediaPlayer: MediaPlayer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_player)
position = intent.getIntExtra("position", -1)
mediaPlayer = MediaPlayer()
songlist = getAudio(this)
if (songlist != null){
pausePlay.setImageResource(R.drawable.ic_pause)
uri = Uri.parse(songlist[position].path)
}
if (mediaPlayer == null){
mediaPlayer = MediaPlayer.create(applicationContext, uri)
mediaPlayer.stop()
mediaPlayer.release()
mediaPlayer.start()
}
else{
mediaPlayer = MediaPlayer.create(this, uri)
mediaPlayer.start()
}
}
private fun getAudio(context: Context): ArrayList<MusicModel> {
val audioList : ArrayList<MusicModel> = ArrayList()
val uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ARTIST
)
val cursor = context.contentResolver.query(
uri, projection, null,
null, null
)
if (cursor != null) {
while (cursor.moveToNext()) {
val album = cursor.getString(0)
val title = cursor.getString(1)
val duration = cursor.getString(2)
val path = cursor.getString(3)
val artist = cursor.getString(4)
val musicModel = MusicModel(album, title, artist, path, duration)
audioList.add(musicModel)
}
cursor.close()
}
return audioList
}
}
这是从日志猫收到的错误 E / AndroidRuntime:致命异常:main 流程:com.example.musicapp,PID:30931 java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.musicapp / com.example.musicapp.PlayerActivity}:java.lang.NullPointerException:MediaPlayer.create(this,uri)不能为null 在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2956) 在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3091) 在android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 在android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 在android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1843)
有人可以帮我解决此问题吗??