Search code examples
javaandroidandroid-mediaplayer

Java NullPointerException Getting Resources


I am writing a simple Android application (which is mainly for me to test whatever I may need to use in a real app) and I need to use a MediaPlayer to play a sound. In this case, I'm using kalimba.mp3 (no capital letters). But when I try to run the app, it instantly crashes because of a null object reference. The error is below, as is my code. The problem is, I don't see a problem with anything, and it gives me no errors while editing my code. How do I stop this from throwing an error? I've never used a MediaPlayer before. Thanks in advance!

Code:

// Player of "kalimba.mp3"
private MediaPlayer kalimbaPlayer = MediaPlayer.create(this, R.raw.kalimba);

// Play/stop the sound    
public void playSound(View view) { kalimbaPlayer.start(); }
public void stopSound(View view) { kalimbaPlayer.stop(); kalimbaPlayer.release(); }

Error:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference

Solution

  • this is presumably your Activity. At the time the fields are initialised, the Activity probably isn't fully ready.

    Instead, initialise the MediaPlayer inside the onCreate() method of the Activity.