Why when I create the MediaPlayer variable in the Main Activity, the app crashes?
( This code works fine )
public class MainActivity extends AppCompatActivity {
MediaPlayer audio = MediaPlayer.create(this, R.raw.my_audio);
public void play(View view){
audio.start();
}
public void pause(View view){
audio.pause();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio = MediaPlayer.create(this, R.raw.my_audio);
}
}
( But this code doesn’t work; the app crashes)
public class MainActivity extends AppCompatActivity {
MediaPlayer audio = MediaPlayer.create(this, R.raw.my_audio);
public void play(View view){
audio.start();
}
public void pause(View view){
audio.pause();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
PLEASE give me an explanation 🙁
3
Answers
in second case you havent created
MediaPlayer
instance at allso every
audio.anyMethodCall()
will throwNullPointerException
just keep
audio = MediaPlayer.create(this, R.raw.my_audio);
line inonCreate
, thats proper place for initing playerand please learn some basics about programming…
oncreate method
You can do something like this
The Correct code should be:
the only change I did was removing declaration before oncreate method:
Earlier:
Correct Code:
Explanation:
MediaPlayer
, definingtextView
, etc, since onCreate() gets triggered after creation of activity(activity_main).