I'm doing an app in Android Studio. I have a problem because I can't put MediaPlayer to my buttons. When button will be pressed, the sound effect starts to play.
How can I use this:
MediaPlayer mp = MediaPlayer.create(this, R.raw.example);
For my buttons onClick methods. When I put mp.start();
in onClick Listener, my app crashes.
This is my code:
public class Activity2 extends AppCompatActivity {
private Button button3;
private Button entrycity;
private static final String NAME = "name";
private boolean isEnabled;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_2);
button3 = findViewById(R.id.button3);
button3.setOnClickListener(onButton1Click);
entrycity = findViewById(R.id.entrycity);
entrycity.setOnClickListener(onButton2Click);
sharedPreferences = getSharedPreferences(NAME, MODE_PRIVATE);
isEnabled = sharedPreferences.getBoolean(winflagi.IS_ENABLED, false);
entrycity.setEnabled(isEnabled);
if (isEnabled){
entrycity.setBackgroundResource(R.drawable.oval);
}
else {
entrycity.setBackgroundResource(R.drawable.oval3);
}
}
private View.OnClickListener onButton1Click = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Activity2.this, flagi1.class));
}
};
private View.OnClickListener onButton2Click = new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Activity2.this, cities1.class));
}
};
}