Search code examples
androidmedia-player

Android - create Utility class to play a sound


I have a sound that I want to be played when a button clicked. The same sound over many activities. So I thought it could be a good idea to create a Utility class that will have the method for playing the sound and I will call it from various activities, instead of creating a MediaPlayer variable in all the other activities. So I created this Utility class:

public class Utilities extends Activity {

public MediaPlayer mpPositive;
public MediaPlayer mpNegative;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mpPositive = MediaPlayer.create(this, R.raw.click_positive);
    mpNegative = MediaPlayer.create(this, R.raw.click_negative);
}


public void playPositive() {
    mpPositive.start();
}

}

In my activity I imported this file. And then I tried to use it like that:

public class ActivityListCategories extends ListActivity implements
     OnClickListener {
        private Utilities myUtilities;
        ...rest of the code...

    public void onCreate(Bundle savedInstanceState) {

    myUtilities = new Utilities();
            ...rest of the code...
            }
    }

public void onClick(View v) {

    switch (v.getId()) {
    case R.id.btnAdd:
        myUtilities.playPositive();
                    ...rest of the code...
}

But when I click the button - my app crashes. What am I doing wrong and how do I fix it?


Solution

  • Your code crashes because the onCreate() method of Utilities is never called as you don't use it as a normal Activity, and it doesn't follow the Activity life cycle. Due to this, your this reference will always be null.

    Instead, try making it a normal Java class, something like:

    public class Utilities extends Activity {
    
        public MediaPlayer mpPositive;
        public MediaPlayer mpNegative;
    
        public Utilities(Context context) {
            mpPositive = MediaPlayer.create(context, R.raw.click_positive);
            mpNegative = MediaPlayer.create(context, R.raw.click_negative);
        }
    
    
        public void playPositive() {
            mpPositive.start();
        }
    
    }
    

    And then create an object as follows:

    Utilities utils = new Utilities(this);
    

    Make sure this line is in onCreate() or after of your main Activity.