title: android studio media player null object reference
body: <p>I ran into trouble when trying to use the media player in Android Studio, it seems like i haven't initialize the media player properly, which caused the app to crash (on phones running on Android 8.0) when SoundFXPlayer.setVolume() function is called. However, the app worked properly in emulator (API 26 - 28) , and most of the phone i tested (phones with on API 26-27) , EXCEPT phones that run on Android 8.0 (API 28)  . 
  To summarize
  1. How to initialize media player properly
  2. Why my code work on emulator but not on phone.</p>
  
  <p>i am new to stackoverflow and not experienced in programming, sorry if didn't gave enough details.</p>
  
  <p>Error message as follow:</p>
  
  <blockquote>
    <p>java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.garmischwong.buttongame/com.example.garmischwong.buttongame.MenuActivity}:
    java.lang.NullPointerException: Attempt to invoke virtual method 'void
    android.media.MediaPlayer.setVolume(float, float)' on a null object
    reference</p>
  </blockquote>
  
  <pre><code>package com.example.garmischwong.buttongame;
  
  import android.content.Intent;
  import android.content.SharedPreferences;
  import android.media.MediaPlayer;
  import android.support.v7.app.AppCompatActivity;
  import android.os.Bundle;
  import android.view.View;
  import android.widget.Button;
  
  
  public class MenuActivity extends AppCompatActivity {
  
  private Button gameButton;
  public int SoundFXVolume;
  public MediaPlayer SoundFXPlayer;
  public static final String GAME_PREF = "gamePref" ;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_menu);
      gameButton = findViewById(R.id.gameButton);
      SoundFXPlayer = MediaPlayer.create(this, R.raw.menu_selection_click);
      loadSoundFX();
      SoundFXPlayer.setVolume((float)SoundFXVolume/100,(float)SoundFXVolume/100);
  }
  
  
  public void goToGameAct(View view)
  {
      //////Intent to game///////
      SoundFXPlayer.start();
      Intent goToGameIntent = new Intent(MenuActivity.this, GameActivity.class);
      startActivity(goToGameIntent);
      finish();
  }
  
  public void loadSoundFX()
      {
          SharedPreferences gamePref = getSharedPreferences(String.valueOf(GAME_PREF), MODE_PRIVATE);
          SoundFXVolume = gamePref.getInt("Sound_FX_Volume", 30);
      }
  </code></pre>