简体   繁体   中英

Null point exception when loading a 'raw' MediaPlayer resource in two activities

I am struggling with loading a sound in my application. I'm receiving a null point exception when trying to create the same "sound" in two activities. I have a variable clickSound that i declare in both activities which accesses the same Raw file. I have added a folder named 'raw' in the 'res' folder and the file clicksound.mp3 in it.

The thing is, for MainActivity is working perfect. for Second activity i just receive the exception.

Main Activity:

// Declare clickSound onCreate
        final MediaPlayer clickSound = MediaPlayer.create(this, R.raw.click_button);

Second Activity:

private final MediaPlayer mClickSound = MediaPlayer.create(this, R.raw.click_button);

The strange thing is that it worked some time ago but now i don't understand why not anymore. Any suggestions what is happening?

This line:

private final MediaPlayer mClickSound = MediaPlayer.create(this, R.raw.click_button);`

for that moment the instace in not valid initialized, so this is not givin all that you need to create a media player.... move that to the onCreate method

I think this error is related when you don't initialize your class.

Try before something like this:

MediaPlayer mClickSound = new MediaPlayer();

Or full code:

private final MediaPlayer mClickSound;
//other things
MediaPlayer mClickSound = new MediaPlayer();
mClickSound = MediaPlayer.create(this, R.raw.click_button);

It could be also that you're using two different names "clickSound" and "mClickSound"

The problem was not with the MediaPlayer file. I had an error with my Json Reader that was not handling well an exception.

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