简体   繁体   中英

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

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 .

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 MainActivity s 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, Activity s 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 Activity s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM