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 sollution.
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.