当我按下下一个按钮时,我想进入下一个布局并停止播放音乐。 如果我按下播放按钮并按下下一个按钮应用程序正在运行。
但是,如果音乐没有播放,我推到下一个布局按钮,应用程序崩溃,因为即使音乐没有播放,我的代码也会尝试停止。我该怎么办?
package com.gamedom.relaxingmusic;
import gif.decoder.GifRun;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
public class Music1 extends Activity {
public static MediaPlayer mp1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music1);
final ImageButton Start1 =(ImageButton) findViewById(R.id.btnStart1);
final ImageButton Stop1 =(ImageButton) findViewById(R.id.btnStop1);
ImageButton SOL1 =(ImageButton) findViewById(R.id.btnSol1);
ImageButton SAG1 =(ImageButton) findViewById(R.id.btnSag1);
Stop1.setVisibility(View.INVISIBLE);
Start1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp1=MediaPlayer.create(Music1.this, R.raw.firefurnace);
mp1.start();
mp1.setLooping(true);
Start1.setVisibility(View.INVISIBLE);
Stop1.setVisibility(View.VISIBLE);
}
});
Stop1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp1.stop();
mp1.release();
Stop1.setVisibility(View.INVISIBLE);
Start1.setVisibility(View.VISIBLE);
}
});
//////NEXT LAYOUT BUTTON \\\\\\\\\
SAG1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.stop();
}
startActivity(new Intent("android.intent.action.MUSIC2"));
}
});
////// BACK LAYOUt BUTTON \\\\\\\\\
SOL1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mp1.isPlaying()) {
mp1.stop();
}
startActivity(new Intent("android.intent.action.MUSIC4"));
}
});
}
问题在这里
SOL1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//It try to stoping the music but it's already stopped program is crashes
if (mp1.isPlaying()) {
mp1.stop();
}
startActivity(new Intent("android.intent.action.MUSIC4"));
}
});
答案 0 :(得分:0)
看起来您在onClick中初始化媒体播放器对象。因此,如果未触发该事件,则您的mp1
变量将为null。我相信你得到NullPointerException
。