I am new to java and I don't know what to do. This is the code that I am trying to do, what I need is to mute the sound effects that are playing to other buttons using another button (playstop) and to also unmute the effects using the same button (playstop).
MediaPlayer audio1, audio2, audio3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
audio1 = MediaPlayer.create(MainActivity.this, R.raw.addlife);
audio2 = MediaPlayer.create(MainActivity.this, R.raw.freeeze);
audio3 = MediaPlayer.create(MainActivity.this, R.raw.highlight);
Button addlife = (Button) findViewById(R.id.button);
Button freeze = (Button) findViewById(R.id.button2);
Button highlight = (Button) findViewById(R.id.button3);
Button playstop = (Button) findViewById(R.id.button4);
addlife.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audio1.start();
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
}
});
freeze.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audio2.start();
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
}
});
highlight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
audio3.start();
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
}
});
i = 0;
playstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
audio1.stop();
audio2.stop();
audio3.stop();
playstop.setBackgroundResource(R.drawable.mute);
i++;
}
else if (i == 1){
audio1.start(); //does not work
audio2.start(); //does not work
audio3.start(); //does not work
playstop.setBackgroundResource(R.drawable.unmute);
i = 0;
}
}
});
}
If you are trying to find which sound is playing right now then MediaPlayer has method - isPlaying(). It returns true if it is playing right now.
In this case you need something like this:
if (audio1.isPlaying()){
audio1.stop()
addLife.setVisibility(View.VISIBLE)
}
If you need to pause/play currently playing sound you can use pause() and start() methods, but in this case you better to make some additional class to handle all manipulations. Example:
import android.media.MediaPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;
public class MediaPlayerManager {
public final HashMap<String, MediaPlayer> mediaPlayerList;
public final ArrayList<String> keys;
private String pausedPlayerKey;
public MediaPlayerManager(MediaPlayer... mediaPlayers) {
mediaPlayerList = new HashMap<>();
keys = new ArrayList<>();
if (mediaPlayers != null && mediaPlayers.length > 0) {
for (MediaPlayer mediaPlayer : mediaPlayers) {
String uid = UUID.randomUUID().toString();
keys.add(uid);
mediaPlayerList.put(uid, mediaPlayer);
}
}
}
public boolean isAnyOnePlaying(){
for (String key : keys) {
MediaPlayer player = mediaPlayerList.get(key);
if (player != null && player.isPlaying()) {
return true;
}
}
return false;
}
public void pauseIfPlaying() {
for (String key : keys) {
MediaPlayer player = mediaPlayerList.get(key);
if (player != null && player.isPlaying()) {
player.pause();
pausedPlayerKey = key;
break;
}
}
}
public void resume() {
if (pausedPlayerKey != null) {
if (mediaPlayerList.containsKey(pausedPlayerKey) && mediaPlayerList.get(pausedPlayerKey) != null) {
Objects.requireNonNull(mediaPlayerList.get(pausedPlayerKey)).start();
pausedPlayerKey = null;
}
}
}
}
Then in onCreate method you can do this.
MediaPlayerManager mpm = new MediaPlayerManager({audio1, audio2, audio3});
And then:
playstop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mpm.isAnyOnePlaying()){
mpm.pauseIfPlaying();
}else {
mpm.resume();
}
//help//
}
});
Related
i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}
In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem
package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}
I am trying to make a app that has a switch a button and a text and if you turn the switch on and press the button; the number displayed on the text will be added by 1. But if the switch is turned off the number will be subtracted by 1.
but when i run my app and press the button, the app crashes...
i do not have much experience at programming and i do not know what im doing wrong. and i have only tried this code.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView text = (TextView)findViewById(R.id.textView);
final Button button = (Button)findViewById(R.id.button);
Switch mySwitch = (Switch)findViewById(R.id.mySwitch);
mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked== true){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(text_int);
}
});
}
if (isChecked == false) {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(text_int);
}
});
}
}
});
}
}
so this should behave as i described earlier but it doesn't.
Your app crashes because you are trying to set an int to a textview.setText()and when you pass an int to this method it expects it to be a resource id and which could not be found in your case that's why it will throw ResourceNotFoundException and crashes.
You should set text as following:
text.setText(String.valueOf(text_int));
You’re nesting listeners but that logic doesn’t work sequentially. You should declare your listeners separately. I suggest you create a boolean that holds the state of the switch and one button listener. Within the listener check if switch is enabled then run your calculations and do the same if the switch is disabled.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mySwitch.isChecked(){
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(String.valueOf(text_int));
} else {
String text_string = text.getText().toString();
int text_int = Integer.parseInt(text_string);
text_int++;
text.setText(String.valueOf(text_int));
}
}
});
You don't need a listener for the Switch, but only 1 listener for the Button:
final TextView text = (TextView)findViewById(R.id.textView);
final Button button = (Button)findViewById(R.id.button);
final Switch mySwitch = (Switch)findViewById(R.id.mySwitch);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text_string = text.getText().toString();
int text_int = 0;
try {
text_int = Integer.parseInt(text_string);
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (mySwitch.isChecked())
text_int++;
else
text_int--;
text.setText("" + text_int);
}
});
Every time you click the Button, in its listener the value in the TextView is increased or decreased depending on whether the Switch is checked or not.
I am facing problem in my app. All the audios are playing well but the problem is when I press on the first button to start playing audio, it plays it and if I click on next play button that also starts playing but the first audio does not stop. how to stop that. please help
Here, my app java code :
public class ringtone_tab extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mdx6 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_vandana);
mdx5 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_tandav_mantra);
mdx4 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv_om);
mdx3 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shiv);
mdx2 = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_aaradhna);
mdx = MediaPlayer.create(ringtone_tab.this,R.raw.shiv_shankar);
}
public void setBtn_play6(View v)
{
if(mdx6.isPlaying())
{
mdx6.stop();
mdx6.reset();
mdx6.release();
}
mdx6 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mdx6.start();
}
public void setBtn_play5(View v)
{
if(mdx5.isPlaying())
{
mdx5.stop();
mdx5.reset();
mdx5.release();
}
mdx5 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mdx5.start();
}
public void setBtn_play4(View v)
{
if(mdx4.isPlaying())
{
mdx4.stop();
mdx4.reset();
mdx4.release();
}
mdx4 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mdx4.start();
}
public void setBtn_play3(View v)
{
if(mdx3.isPlaying())
{
mdx3.stop();
mdx3.reset();
mdx3.release();
}
mdx3 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mdx3.start();
}
public void setBtn_play2(View v)
{
if(mdx2.isPlaying())
{
mdx2.stop();
mdx2.reset();
mdx2.release();
}
mdx2 = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mdx2.start();
}
public void setBtn_play1(View v)
{
if(mdx.isPlaying())
{
mdx.stop();
mdx.reset();
mdx.release();
}
mdx = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mdx.start();
}
}
Introduce new method call like stopAllplayers
private void stopAllPlayers(){
if(mdx1 != null && mdx1.isPlaying())
{mdx1.stop();mdx1.reset(); mdx1.release();}
if(mdx2 != null && mdx2.isPlaying())
{mdx2.stop();mdx2.reset(); mdx2.release();}
if(mdx3 != null && mdx3.isPlaying())
{mdx3.stop();mdx3.reset(); mdx3.release();}
if(mdx4 != null && mdx4.isPlaying())
{mdx4.stop();mdx4.reset(); mdx4.release();}
if(mdx5 != null && mdx5.isPlaying())
{mdx5.stop();mdx5.reset(); mdx5.release();}
if(mdx6 != null && mdx6.isPlaying())
{mdx6.stop();mdx6.reset(); mdx6.release();}
}
then call this method in all of your play methods.
public void setBtn_play6(View v)
{
stopAllPlayers()
........
do this for all setBtn_play1, setBtn_play2.....
Use below code with one media player
public class ringtone_tab extends AppCompatActivity {
Button clk1;
Button clk2;
Button clk3;
Button clk4;
Button clk5;
Button clk6;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtone_tab);
clk6 = (Button) findViewById(R.id.btn_play6);
clk5 = (Button) findViewById(R.id.btn_play5);
clk4 = (Button) findViewById(R.id.btn_play4);
clk3 = (Button) findViewById(R.id.btn_play3);
clk2 = (Button) findViewById(R.id.btn_play2);
clk1 = (Button) findViewById(R.id.btn_play1);
mediaPlayer = new MediaPlayer();
}
public void setBtn_play6(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_vandana);
mediaPlayer.start();
}
public void setBtn_play5(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_tandav_mantra);
mediaPlayer.start();
}
public void setBtn_play4(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv_om);
mediaPlayer.start();
}
public void setBtn_play3(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shiv);
mediaPlayer.start();
}
public void setBtn_play2(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_aaradhna);
mediaPlayer.start();
}
public void setBtn_play1(View v)
{
stopPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shiv_shankar);
mediaPlayer.start();
}
private void stopPlayer(){
if(mediaPlayer != null && mediaPlayer.isPlaying())
{mediaPlayer.stop();}
}
}
I want to add a button in my application that turns off the music but I don't know how to approach it, I have an idea but I'm sure it's far from best so I want to consult with you. The situation is as follows:
public class MainActivity extends Activity implements OnClickListener {
MediaPlayer easysong;
MediaPlayer normalsong;
MediaPlayer hardsong;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.land_main);
mContext = this;
restartButton = (Button)findViewById(R.id.restartButton);
restartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
easysong = MediaPlayer.create(MainActivity.this, R.raw.arideniro);
normalsong = MediaPlayer.create(MainActivity.this, R.raw.junior);
hardsong = MediaPlayer.create(MainActivity.this, R.raw.ketsathis);
counter = 101;
i = 500 - dif;
new Thread(new Runnable() {
public void run() {
if(i==500){
easysong.start();}
else if(i==375){
normalsong.start();
}else if(i==250){
hardsong.start();
}
while (counter > 0) {
try {
Thread.sleep(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter--;
runOnUiThread(new Runnable() {
#Override
public void run() {
scoreText.setText(Integer.toString(counter));
}
});
if(i>150){
i/=1.01;}
else if(i>90-(dif/10)){
i-=1;
}
}if (counter==0) {
mChronometer.stop();
if(easysong.isPlaying()) {
easysong.stop();
easysong.release();
easysong = null;
}else if(normalsong.isPlaying()){
normalsong.stop();
normalsong.release();
normalsong = null;
}else if(hardsong.isPlaying()){
hardsong.stop();
hardsong.release();
hardsong = null;
}
This is the main class of my app where the mediaplayer is used, now I deleted much of the code because it was irrelevant to the mediaplayer and the question, so don't look for the missing brackets and such. And this here is the main menu class where the Switch that will turn on and off the music will be located:
public class MainMenu extends Activity{
private Button easy;
private Button normal;
private Button hard;
private Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
easy = (Button) findViewById(R.id.btn_easy);
scores = (Button) findViewById(R.id.btn_highscores);
easy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dif = 0;
startGame();
}
});
}
public void startGame() {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
So my idea is simnple, to add a variable in MainActivity like "int p;" and from the MainMenu class to change it's state between 0 and 1, then I will add around each line that starts music an if(p==1) but is this a good approach ? Also I would like the value of the int to be saved when the app is closed