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?
Your code crashes because the
onCreate()method ofUtilitiesis never called as you don’t use it as a normalActivity, and it doesn’t follow the Activity life cycle. Due to this, yourthisreference will always be null.Instead, try making it a normal Java class, something like:
And then create an object as follows:
Make sure this line is in
onCreate()or after of your main Activity.