Reputation: 1550
I've got a MediaPlayer which works fine and the stop button works okay. However if the user goes into the activity and presses the stop button without playing any music, the app crashes. If a song is played, the user can press the stop button as many times as they wish and it works fine. Any help would be awesome!
public class Website extends AppCompatActivity {
private MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridviewmusic);
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(this));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
stopPlaying();
mp = MediaPlayer.create(Website.this, R.raw.sound1);
mp.start();
// This will make sound
break;
case 1:
stopPlaying();
mp = MediaPlayer.create(Website.this, R.raw.sound2);
mp.start();
break;
case 2:
stopPlaying();
mp = MediaPlayer.create(Website.this, R.raw.sound3);
mp.start();
break;
case 3:
stopPlaying();
mp = MediaPlayer.create(Website.this, R.raw.sound4);
mp.start();
break;
case 4:
stopPlaying();
mp = MediaPlayer.create(Website.this, R.raw.sound5);
mp.start();
break;
case 5:
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://play.google.com/store/music/"));
startActivity(i);
break;
}
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
}
});
}
private void stopPlaying() {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
if(mp!= null)
{
mp.stop();
mp=null;
}
this.finish();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
if(mp!= null)
{
mp.stop();
mp=null;
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Upvotes: 0
Views: 1036
Reputation: 539
Try this:
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp!=null && mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
}
});
Upvotes: 1