Reputation: 111
I'm pretty new to Kotlin and I'm trying to create some exercise application in Android Studio. Now, I am using the Fragment Architecture for my app. I have a problem while trying to play a particular song on a fragment when I press a button to activate it.
private var mediaPlayer: MediaPlayer? = MediaPlayer.create(context, R.raw.workout_music)
and then in my onCreateView function:
mediaPlayer?.start()
and getting this error:
android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment com.example.bitamirshafiee.fitnessapp.ExerciseFragment: calling Fragment constructor caused an exception
at android.support.v4.app.Fragment.instantiate(Fragment.java:465)
Upvotes: 0
Views: 146
Reputation: 2126
context
is null
, because the constructor is called outside of the lifecycle, in field declaration, where context
is not yet made. So that is why it can crash.
Making mediaPlayer
a lateinit
variable would remove the need for nullability. private lateinit var mediaPlayer: MediaPlayer
then in onCreateView
it could be initialised like mediaPlayer = MediaPlayer.create(context, R.raw.workout_music)
.
Upvotes: 1