ImageButton crashes when trying to play a sound
When trying to make a sound when clicked on an ImageButton my application crashes and I've been staring at my code for quite some time now without finding an answer. I was hoping you guys could help me see what I'm doing wrong.
I tried to make the onClick event manually with the imageButton which failed and then I tried it through the drag and drop system of Eclipse, which made the button clickable through a method I named test123 via the main.xml.
I'll post my code and hope you guys can find a s开发者_如何学JAVAollution.
Thanks in advance,
package com.example.Jeffrey;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class Jeffrey extends Activity {
MediaPlayer mp;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.noise);
// View rakker = findViewById(R.id.imageView1);
//rakker.setOnClickListener(this);
}
public void test123()
{
mp.start();
}
}
The xml that goes with the code:
<ImageButton
android:src="@drawable/rakker"
android:layout_height="250px"
android:layout_width="wrap_content" android:id="@+id/imageView1"
android:onClick="test123"></ImageButton>
It's probably worth checking for a null value considering it returns that if for any reason it fails to create the MediaPlayer object. Also, it should probably get released when finished (also with a null check).
EDIT:
while my earlier answer might be worth considering, it is definitely necessary that you have your onClick method take a View as a parameter.
//at the top of the file
import android.view.View;
public void test123(View v){
//v is the view that has been clicked (the ImageButton from your .xml file)
//do stuff
}
Based on code put up in the poset, I could say that issue is related to MediaPlayer usage. MediaPlayer has several states, idle, initialized, prepared, started etc.
In your code, You create the media player object by passing resource id; making media player enter initialized state from idle. Next you need to invoke prepare(). But you are calling start(). May be this is causing the crash.
The MediaPlayer's state transition is neatly explained in android developer website. (Link)
Shash
prepare the MediaPlayer with mp.prepare(); before calling mp.start();
精彩评论