Reputation: 345
I just made an example app for playing a sound. Playing works but if i press the button my app crashes. The code seems to be correct in my eyes:
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playAlarm();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new ButtonClick());
}
private void playAlarm() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
try {
mediaPlayer.setDataSource(this, alert);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class ButtonClick implements View.OnClickListener {
@Override
public void onClick(View v) {
mediaPlayer.stop(); //Getting a NullPointerException
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I don't have any idea how to fix this. Thanks in advance!
Upvotes: 0
Views: 65
Reputation: 5971
Provided that you do have playAlarm() happen before you click on the button. you need mediaPlayer = new MediaPlayer() before mediaPlayer.setDataSource(this, alert); (there's other errors here too, but that's the cause of the NPE). You should also remove e.printstackTrace() and just let it happen.
Upvotes: 1