You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用android.media.MediaPlayer.start()触发空对象引用异常求助

Fixing "Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference"

Hey there, that null pointer exception is a super common gotcha with Android's MediaPlayer—let's break down why it's happening and how to fix it.

Why this happens

You've declared the MediaPlayer mpplayer; variable, but you never initialized it before calling start(). The variable is still null when you try to call a method on it, hence the crash.

How to fix it

You need to initialize the MediaPlayer instance properly before using it. Here are the two most common scenarios:

1. Initializing from a raw resource (e.g., audio in res/raw folder)

This is the simplest approach because MediaPlayer.create() handles initialization and preparation automatically:

// Put this in your onCreate() method, after setting the content view
mpplayer = MediaPlayer.create(this, R.raw.your_audio_file);

Note: Don't call prepare() when using create()—it's already done for you.

2. Initializing from a file path or URI

If you're loading audio from a local file or remote URL, you'll need to manually set the data source and prepare the player:

mpplayer = new MediaPlayer();
try {
    // Replace with your file path or URI
    mpplayer.setDataSource(this, Uri.parse("/sdcard/your_audio.mp3"));
    mpplayer.prepare(); // Critical step—don't skip this!
} catch (IOException e) {
    e.printStackTrace();
    // Add error handling here (e.g., show a toast to the user)
}

Bonus: Prevent future crashes & memory leaks

  • Always check if the MediaPlayer is not null before calling methods on it:
    if (mpplayer != null && mpplayer.isPrepared()) {
        mpplayer.start();
    }
    
  • Release the MediaPlayer when your activity is destroyed to avoid memory leaks:
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mpplayer != null) {
            mpplayer.release();
            mpplayer = null;
        }
    }
    

Example integrated into your code

Here's how your onCreate() might look with the raw resource initialization:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    mb1 = findViewById(R.id.your_button_id);
    // Initialize MediaPlayer
    mpplayer = MediaPlayer.create(this, R.raw.your_audio);
    
    mb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mpplayer != null) {
                mpplayer.start();
            }
        }
    });
}

内容的提问来源于stack exchange,提问作者zheng zheng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:42:31