Search code examples
javaandroidandroid-mediaplayer

Why does MediaPlayer.create throw NullPointer exception when initialised in the beginning of the class but not when initialised in OnCreate method?


When initialising a MediaPlayer object using a context and resource in the beginning of the class, it throws a NullPointer exception, but when declaring it in the beginning of the class (therefore it is null) and then initialising it in the same way in the onCreate method, it works. This also happens to me with other objects such as views and I cannot understand why as it is initialised in the same way.

public class MainActivity extends AppCompatActivity {

//Commented code is how it is written to run without problems

//  private MediaPlayer player;

    private MediaPlayer player = MediaPlayer.create(this, R.raw.test); //Throws NullPointer Exception

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        player = MediaPlayer.create(this, R.raw.test);

        setContentView(R.layout.activity_main);
    }
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android.musicplayer, PID: 17008
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.musicplayer/com.example.android.musicplayer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3066

Solution

  • Welcome to Stackoverflow.

    As the error estates, the create method needs a context. This context is only created on the onCreate method of the activity. That said, when you are creating your variable, there isn't a context, cause onCreate didn't happen yet.

    Make the following changes:

    public class MainActivity extends AppCompatActivity {
    
    //Commented code is how it is written to run without problems
    
    //  private MediaPlayer player;
    
    private MediaPlayer player; //Remove the MediaPlayer.create from here
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    //        player = MediaPlayer.create(this, R.raw.test);
    
        setContentView(R.layout.activity_main);
    
        player = MediaPlayer.create(this, R.raw.test); //and put it here
    
    }