Takuya2412 :
In my MainActivity class I have this little function to play music
MediaPlayer player1;
if(player1 == null){
player1 = MediaPlayer.create(this, R.raw.song1);
player1.start();
}
It works very fine but I want to use this for other activty too so I created a MusicPlayer class
MediaPlayer player;
public void play(Context c, @RawRes int sound){
if (player == null){
player = MediaPlayer.create(c, sound);
}
player.start();
}
So what I want to do is, to pass a R.raw.song
to the play()
method. I could pass it by the parameter @RawRes int sound
What my problem is, how can I pass this
?
I tried this in my MainActivity Class
MusicPlayer playboy;
playboy.play(this, R.raw.song1);
But I get an error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.japan, PID: 32764
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.japan/com.example.japan.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.japan.Helper.MusicPlayer.play(android.content.Context, int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3333)
I also tried to pass MainActivity.this
but same error.
What am I doing wrong?
Gurgen Gevondov :
You need to create your MusicPlayer object first. Try this code in your MainActivity class
MusicPlayer playboy = new MusicPlayer();
playboy.play(this, R.raw.song1);
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=403928&siteId=1