Nullpointerexception While Using Android's Mediaplayer
Solution 1:
It seems the MediaPlayer
cannot be created, the create()
method returning a null
pointer. The official doc says this happens when the creation fails, with no further details.
You said this happens when you click several times in a row on the button that leads this method to be called. This is probably due to a non reentrancy issue.
You should try to surround the MediaPlayer
creation and usage by a flag that would prevent reentrancy:
publicvoidfalseAnswerPoints() {
if (!mPlayingSound) {
mPlayingSound = true;
MediaPlayer playError = MediaPlayer.create(QuizActivity.this, R.raw.error);
playError.start();
}
}
mPlayingSound
being a private boolean
member initialized to false
and that you would reset to false
once the MediaPlayer
would have finished playing (using public void setOnCompletionListener (MediaPlayer.OnCompletionListener listener)
should be fine, although I am not sure whether it is called in case of abnormal or anticipated termination of the play).
EDIT: There is a NullPointerException so there is a stack trace. To capture the stack trace, in debug only (the code below is not suitable for release), you can do as follows:
publicvoidfalseAnswerPoints() {
try {
MediaPlayer playError = MediaPlayer.create(QuizActivity.this, R.raw.error);
playError.start();
}
catch (NullPointerException e) {
// Set a breakpoint there to inspect the state of your app// Then rethrow the exception to have it logged, and why not// log extra info.
}
}
Solution 2:
I'm afraid all answers here are wrong. I encountered this issue, albeit more than a year later, but after some research found the answer. It's in two parts.
- Best to start the mediaplayer AFTER the declaration of the onCompleteListener. This insures that the mediaplayer has a full list of instructions declared before it even start playing.
- Use a statically declared object called an AtomicBoolean. This insures that there is only one boolean parameter, and that the process is locked until it finishes the process. This is the only way to insure a process is thread safe.
Hope you found this useful (all future programmers that encounter this problem) ;-)
Solution 3:
To solve your problem you can try to write a permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in manifest
Post a Comment for "Nullpointerexception While Using Android's Mediaplayer"