调用android.media.MediaPlayer.start()触发空对象引用异常求助
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

