• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Help:Simple two buttons [Solved]

Hello, I'm getting no errors. My app contains two buttons, where each, when clicked plays a different sound located in the raw folder. The first button plays, but the second button does not.

Below is the updated code for two buttons that plays a sound onclick, it now works. I hope this helps! thank you LV426, for your help.

package com.example.student.blessyou;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;




public class MainActivity extends AppCompatActivity {
AdView adView;
Button btn_bless_you;
Button buttonThankYou;


private MediaPlayer mp;

@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonThankYou = (Button) findViewById(R.id.buttonThankYou);
btn_bless_you = (Button) findViewById(R.id.btn_bless_you);


btn_bless_you.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
stopPlaying();
mp = MediaPlayer.create(MainActivity.this,R.raw.bless_you);
mp.start();

}
});



buttonThankYou.setOnClickListener(new View.OnClickListener() {
@override
public void onClick (View v){
stopPlaying();
mp = MediaPlayer.create(MainActivity.this, R.raw.thank_you);
mp.start();

}
});
}

private void stopPlaying() {
if (mp !=null){
mp.stop();
mp.release();
mp = null;
}

adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);

}

}
 
Last edited:
Don't create MediaPlayer object in onCreate method of activity, instead instantiate them in response to button events but make sure that you call stop()and release() before start media player,
 
okay I added MainAcitivity to the mp

Now both buttons dont work.

Can you clarify how they don't work? Also post your updated code.
The key thing, as mentioned above, is that you call stop() and release() before playing another sound with the MediaPlayer.
 
You should only use one MediaPlayer object. Stop and release the MediaPlayer when you click the Button. Re-initialise it for the selected sound.
There's a good example in the answer to this question. Use the same pattern

http://stackoverflow.com/questions/12266502/android-mediaplayer-stop-and-play

Thank you so much. What I did not realize was, I had an extra button on click method after my adview. Once I deleted that everything works. I appreciate all your help. The funny thing is I searched all through StackOverflow for examples, then boom...your link was perfect. I will post the fixed code so others can find here also.
 
Back
Top Bottom