How to pass Activity.class (this) to a method? (Android)

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);

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);

So what I want to do is, to pass a 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;, 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, int)' on a null object reference

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();, R.raw.song1);

Guess you like