kotlin.TypeCastException: null не может быть отброшен в ненулевой тип kotlin.Long

Мне нужно удалить эту ошибку очень быстро, поэтому, пожалуйста, помогите мне.

Этот код является кодом для SongsPlayingFragment и ошибка указана в разделе журналов.

Я пытаюсь создать приложение Music Player. Всякий раз, когда я открываю приложение и нажимаю на любую песню, открывается экран воспроизведения, а затем происходит сбой приложения.

журнал дает ошибку при отображении, которую я не могу понять.

Любая помощь высоко ценится

КОД: –

package com.vikanshu.echo.Fragments import android.app.Activity import android.content.Context import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.Bundle import android.os.Handler import android.support.v4.app.Fragment import android.support.v7.widget.DialogTitle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.SeekBar import android.widget.TextView import com.vikanshu.echo.CurrentSongHelper import com.vikanshu.echo.R import com.vikanshu.echo.SongsDataType import kotlinx.android.synthetic.main.fragment_song_playing.* import java.util.* import java.util.concurrent.TimeUnit class SongPlayingFragment : Fragment() { var myActivity: Activity ?= null var mediaPlayer: MediaPlayer ?= null var songName: TextView ?= null var artistName: TextView ?= null var seekBar : SeekBar ?= null var startTime: TextView ?= null var stopTime: TextView ?= null var playPause: ImageButton ?= null var previousSong: ImageButton ?= null var nextSong: ImageButton ?= null var loopSong: ImageButton ?= null var shuffleSongs: ImageButton ?= null var currentSongHelperObject: CurrentSongHelper ?= null var currentPosition: Int = 0 var fetchSongs: ArrayList<SongsDataType> ?= null var updateSongTime = object : Runnable{ override fun run() { val getCurrent = mediaPlayer?.currentPosition startTime?.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long), TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong() as Long) - TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long)) )) Handler().postDelayed(this,1000) } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { var view = inflater!!.inflate(R.layout.fragment_song_playing, container, false) songName = view?.findViewById(R.id.songName) artistName = view?.findViewById(R.id.songArtist) seekBar = view?.findViewById(R.id.seekBar) startTime = view?.findViewById(R.id.startTime) stopTime = view?.findViewById(R.id.endTime) playPause = view?.findViewById(R.id.playPauseButton) previousSong = view?.findViewById(R.id.playPreviousButton) nextSong = view?.findViewById(R.id.playNextButton) loopSong = view?.findViewById(R.id.loopButton) shuffleSongs = view?.findViewById(R.id.shuffleButton) return view } override fun onAttach(context: Context?) { super.onAttach(context) myActivity = context as Activity } override fun onAttach(activity: Activity?) { super.onAttach(activity) myActivity = activity } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) currentSongHelperObject = CurrentSongHelper() currentSongHelperObject?.isPlaying = true currentSongHelperObject?.isLoop = false currentSongHelperObject?.isShuffle = false var path: String ?= null var _songTitle: String ?= null var _songID: Long ?= null var _songArtist: String ?= null try { path = arguments.getString("path") _songArtist = arguments.getString("songArtist") _songTitle = arguments.getString("songTitle") _songID = arguments.getInt("songID").toLong() currentSongHelperObject?.songPath = path currentSongHelperObject?.songArtist = _songArtist currentSongHelperObject?.songId = _songID currentSongHelperObject?.songTitle = _songTitle currentPosition =arguments.getInt("songPosition") fetchSongs = arguments.getParcelableArrayList("songData") currentSongHelperObject?.currentPosition = currentPosition updateTextViews(currentSongHelperObject?.songTitle as String,currentSongHelperObject?.songArtist as String) }catch (e: Exception){ e.printStackTrace() } mediaPlayer = MediaPlayer() mediaPlayer?.setAudioStreamType(AudioManager.STREAM_MUSIC) try { mediaPlayer?.setDataSource(myActivity,Uri.parse(path)) }catch (e: Exception){ e.printStackTrace() } mediaPlayer?.start() processInformation(mediaPlayer as MediaPlayer) if(currentSongHelperObject?.isPlaying as Boolean){ playPause?.setBackgroundResource(R.drawable.pause_icon) }else{ playPause?.setBackgroundResource(R.drawable.play_icon) } mediaPlayer?.setOnCompletionListener { onSongComplete() } clickHandler() } fun onSongComplete(){ if(currentSongHelperObject?.isShuffle as Boolean){ playNext("PlayShuffle") currentSongHelperObject?.isPlaying = true }else{ if (currentSongHelperObject?.isLoop as Boolean){ currentSongHelperObject?.isPlaying = true var nextSong = fetchSongs?.get(currentPosition) currentSongHelperObject?.songTitle = nextSong?.songTittle currentSongHelperObject?.songPath = nextSong?.songData currentSongHelperObject?.songId = nextSong?.songId as Long currentSongHelperObject?.currentPosition = currentPosition updateTextViews(currentSongHelperObject?.songTitle as String,currentSongHelperObject?.songArtist as String) mediaPlayer?.reset() try { mediaPlayer?.setDataSource(myActivity,Uri.parse(currentSongHelperObject?.songPath)) mediaPlayer?.prepare() mediaPlayer?.start() processInformation(mediaPlayer as MediaPlayer) }catch (e: Exception){ e.printStackTrace() } }else{ playNext("playNextNormal") currentSongHelperObject?.isPlaying = true } } } fun clickHandler() { shuffleButton?.setOnClickListener({ if(currentSongHelperObject?.isShuffle as Boolean){ shuffleButton?.setBackgroundResource(R.drawable.shuffle_white_icon) currentSongHelperObject?.isShuffle = false }else{ currentSongHelperObject?.isShuffle = true currentSongHelperObject?.isLoop = false shuffleSongs?.setBackgroundResource(R.drawable.shuffle_icon) loopButton?.setBackgroundResource(R.drawable.loop_white_icon) } }) loopButton?.setOnClickListener({ if(currentSongHelperObject?.isLoop as Boolean) { currentSongHelperObject?.isLoop = false loopButton?.setBackgroundResource(R.drawable.loop_white_icon) }else{ currentSongHelperObject?.isLoop = true currentSongHelperObject?.isLoop = false loopButton?.setBackgroundResource(R.drawable.loop_icon) } }) playPauseButton?.setOnClickListener({ if(mediaPlayer?.isPlaying as Boolean){ mediaPlayer?.pause() currentSongHelperObject?.isPlaying = false playPause?.setBackgroundResource(R.drawable.play_icon) }else{ mediaPlayer?.start() currentSongHelperObject?.isPlaying = true playPause?.setBackgroundResource(R.drawable.pause_icon) } }) playNextButton?.setOnClickListener({ currentSongHelperObject?.isPlaying = true if(currentSongHelperObject?.isShuffle as Boolean){ playNext("PlayShuffle") }else{ playNext("playNextNormal") } }) playPreviousButton?.setOnClickListener({ currentSongHelperObject?.isPlaying = true if (currentSongHelperObject?.isLoop as Boolean) loopButton?.setBackgroundResource(R.drawable.loop_white_icon) playPrevious() }) } fun playNext(check: String){ if(check.equals("playNextNormal",true)){ currentPosition = currentPosition + 1 }else if (check.equals("PlayShuffle",true)){ var randonObject = Random() var randomPosition = randonObject.nextInt(fetchSongs?.size?.plus(1) as Int) currentPosition = randomPosition } if(currentPosition == fetchSongs?.size){ currentPosition = 0 } currentSongHelperObject?.isLoop = false var nextSong = fetchSongs?.get(currentPosition) currentSongHelperObject?.songTitle = nextSong?.songTittle currentSongHelperObject?.songArtist = nextSong?.songArtist currentSongHelperObject?.songPath = nextSong?.songData currentSongHelperObject?.songId = nextSong?.songId as? Long updateTextViews(currentSongHelperObject?.songTitle as String,currentSongHelperObject?.songArtist as String) mediaPlayer?.reset() try { mediaPlayer?.setDataSource(myActivity,Uri.parse(currentSongHelperObject?.songPath)) mediaPlayer?.prepare() mediaPlayer?.start() processInformation(mediaPlayer as MediaPlayer) }catch (e: Exception){ e.printStackTrace() } } fun playPrevious(){ currentPosition = currentPosition - 1 if(currentPosition == -1) currentPosition = 0 if (currentSongHelperObject?.isPlaying as Boolean) playPauseButton?.setBackgroundResource(R.drawable.pause_icon) else playPauseButton?.setBackgroundResource(R.drawable.play_icon) currentSongHelperObject?.isLoop = false val nextSong = fetchSongs?.get(currentPosition) currentSongHelperObject?.songTitle = nextSong?.songTittle currentSongHelperObject?.songArtist = nextSong?.songArtist currentSongHelperObject?.currentPosition = currentPosition currentSongHelperObject?.songId = nextSong?.songId as Long updateTextViews(currentSongHelperObject?.songTitle as String,currentSongHelperObject?.songArtist as String) mediaPlayer?.reset() try { mediaPlayer?.setDataSource(activity,Uri.parse(currentSongHelperObject?.songPath)) mediaPlayer?.prepare() mediaPlayer?.start() processInformation(mediaPlayer as MediaPlayer) }catch (e: Exception){ e.printStackTrace() } } fun updateTextViews(songTitle: String,songArtist: String){ songTittle.setText(songTitle) songArtistXYZ.setText(songArtist) } fun processInformation(mediaplayer: MediaPlayer){ val finalTimeXYZ = mediaplayer.duration val startTimeXYZ = mediaplayer.currentPosition startTime?.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(startTimeXYZ?.toLong() as Long), TimeUnit.MILLISECONDS.toSeconds(startTimeXYZ?.toLong() as Long) - TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(startTimeXYZ?.toLong() as Long)))) endTime?.setText(String.format("%d:%d", TimeUnit.MILLISECONDS.toMinutes(finalTimeXYZ?.toLong() as Long), TimeUnit.MILLISECONDS.toSeconds(finalTimeXYZ?.toLong() as Long) - TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(finalTimeXYZ?.toLong() as Long)))) seekBar?.setProgress(startTimeXYZ) Handler().postDelayed(updateSongTime,1000) } } 

LOGS: –

 11-10 02:10:27.941 2706-2721/com.vikanshu.echo E/libEGL: load_driver(/system/lib/egl/libGLES_emulation.so): dlopen failed: library "/system/lib/egl/libGLES_emulation.so" not found 11-10 02:10:28.127 2706-2721/com.vikanshu.echo E/EGL_emulation: tid 2721: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH) 11-10 02:10:29.500 2706-2721/com.vikanshu.echo E/EGL_emulation: tid 2721: eglSurfaceAttrib(1174): error 0x3009 (EGL_BAD_MATCH) 11-10 02:10:40.882 2706-2706/com.vikanshu.echo E/MediaPlayer: start called in state 1, mPlayer(0x0) 11-10 02:10:40.883 2706-2706/com.vikanshu.echo E/MediaPlayer: error (-38, 0) 11-10 02:10:40.883 2706-2706/com.vikanshu.echo E/MediaPlayer: Attempt to call getDuration in wrong state: mPlayer=0x0, mCurrentState=0 11-10 02:10:40.912 2706-2706/com.vikanshu.echo E/MediaPlayer: Error (-38,0) 11-10 02:10:40.914 2706-2706/com.vikanshu.echo E/AndroidRuntime: FATAL EXCEPTION: main Process: com.vikanshu.echo, PID: 2706 kotlin.TypeCastException: null cannot be cast to non-null type kotlin.Long at com.vikanshu.echo.Fragments.SongPlayingFragment.playNext(SongPlayingFragment.kt:235) at com.vikanshu.echo.Fragments.SongPlayingFragment.onSongComplete(SongPlayingFragment.kt:160) at com.vikanshu.echo.Fragments.SongPlayingFragment$onActivityCreated$1.onCompletion(SongPlayingFragment.kt:132) at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:2943) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:154) at android.app.ActivityThread.main(ActivityThread.java:6119) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

    Вы получаете эту ошибку, потому что пытаетесь передать null в Long :

     val x: Long? = null as Long // >>> Exception in thread "main" kotlin.TypeCastException: // >>> null cannot be cast to non-null type kotlin.Long 

    Чтобы исправить это, вы можете использовать безопасный оператор литья :

     val x: Long? = null as? Long println(x) // >>> null 

    Но вам лучше понять, почему вы получаете null значение.