正如标题所述,当我单击按钮播放随机媒体时,我的应用程序崩溃了。
Play random sound on button click
我的目标是当我单击一个按钮时播放随机声音,然后在我单击另一个按钮时停止播放此随机声音。
错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: fr.gab.artapp, PID: 12727
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
at fr.gab.artapp.Activity_good.playRandomSound(Activity_good.java:61)
at fr.gab.artapp.Activity_good.access$000(Activity_good.java:20)
at fr.gab.artapp.Activity_good$1.onClick(Activity_good.java:45)
at android.view.View.performClick(View.java:5210)
at android.view.View$PerformClick.run(View.java:20976)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
活动:
public class Activity_good extends AppCompatActivity {
List<Integer> soundList = new ArrayList<Integer>();
public void setSoundList(List<Integer> soundList) {
soundList.add(R.raw.piano);
soundList.add(R.raw.pnl);
soundList.add(R.raw.david);
}
private AppCompatImageButton backGood;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_good);
// Random text and random sound
final TextView txtBien = (TextView) findViewById(R.id.txtBien);
Button genBien = (Button) findViewById(R.id.genBien);
final String[] pBien={"« Pour réussir, votre désir de réussite doit être plus grand que votre peur de l’échec. » Bill Cosby", "trql", "oui", "non"};
genBien.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int rando = (int) (Math.random()*4);
txtBien.setText(pBien[rando]);
playRandomSound();
}
});
//Change activity and stop the sound
backGood = (AppCompatImageButton) findViewById(R.id.backGood);
backGood.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openMainActivity();
// Stop the sound
}
});
}
private void playRandomSound() {
int randomInt = (new Random().nextInt(soundList.size()));
int sound = soundList.get(randomInt);
MediaPlayer mp = MediaPlayer.create(this, sound);
mp.start();
}
public void openMainActivity(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}