Moosa
Moosa

Reputation: 127

Call a non-static method from static inner class

I'm new to Android, I'm facing this problem that when I call a non-static method from static inner class I have nullPointerException, Below is my code.

public void playPauseMusic() {
    // check for already playing
    if (mp.isPlaying()) {
        if (mp != null) {
            mp.pause();
            // Changing button image to play button
            btnPlay.setImageResource(R.drawable.btn_play);
        }
    } else {
        // Resume surah
        if (mp != null) {
            mp.start();
            // Changing button image to pause button
            btnPlay.setImageResource(R.drawable.btn_pause);
        }
    }
}

public static class notifyPlayPauseListner extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("PLAY/Pause Tag","In the listener Play/Pause  ");
        MainActivity mc = new MainActivity();
        mc.playPauseMusic();
    }
}

May be its a simple concept but I'm new to android that's why asking. Kindly Help

Upvotes: 3

Views: 662

Answers (2)

FD_
FD_

Reputation: 12919

Most likely, this part of your code does not work as you expect it:

MainActivity mc = new MainActivity();
mc.playPauseMusic();

This actually creates a new instance of MainActivity, and calls its method playPauseMusic(). The new MainActivitys mp is null, so accessing it leads to the NPE.

The problem is, new MainActivity(); does not return an already running instance of the activity, as you seem to be expecting. Even worse: That's not the way you instantiate an Activity. Usually, Activitys are started via Intents that are resolved by the system. All instantiation of the Activity is done by the system, and that's the only way for the Activity to get its Context.

Have a look at this question on how to start Activitys from a BroadcastReceiver, if that's what you want. Also note that playing music in the background from an Activity is a bad idea. Using a Service is recommended.

Upvotes: 2

babis
babis

Reputation: 228

MainActivity mc = new MainActivity();

Instantiating a new activity doesn't make any sense. Instead, you need to find the existing instance of MainActivity and call it's desired method.

Also, using an activity to play music isn't really a good idea. Consider using a service.

Upvotes: 3

Related Questions