0
我剛做了一個播放聲音的示例應用程序。玩的作品,但如果我按下按鈕我的應用程序崩潰。代碼似乎是在我眼中是正確的:MediaPlayer崩潰onStop()
public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playAlarm();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new ButtonClick());
}
private void playAlarm() {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
try {
mediaPlayer.setDataSource(this, alert);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mediaPlayer.setLooping(true);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private class ButtonClick implements View.OnClickListener {
@Override
public void onClick(View v) {
mediaPlayer.stop(); //Getting a NullPointerException
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我不知道如何解決這個問題。 在此先感謝!
你正在得到什麼錯誤?另外,發佈堆棧跟蹤 – CarCzar 2014-09-26 21:55:26