I am creating a soundboard app. The app will feature different "pages" (fragments) that the user can switch between. Each fragment has a number of ImageButtons that, when clicked on, will play a sound.
I put the following code first inside of the MainActivity inside the OnCreate method. After that failed I realized that I'd probably have to put that code inside of each fragment inside the fragment's OnCreateView method.
After doing so I come up for an error for the "findViewById" method. I corrected this by using the "getView()" method directly before the "findViewById" method.
Now I have an error on the "final MediaPlayer player = new MediaPlayer();". The error says that this is an unreachable statement.
I have no idea how to fix this... what can I do to correct this error?
FragmentPage1.java
public static class FragmentPage1 extends Fragment {
int selectedSoundId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_page1, container, false);
return rootView;
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
final int[] buttonIds = { R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9 };
final int[] soundIds = { R.raw.num_21, R.raw.whats_9_plus_10, R.raw.a_potato_flew_around_my_room, R.raw.a_week_ago, R.raw.aint_nobody_got_time_for_dat, R.raw.awww, R.raw.baby_lip, R.raw.backflip, R.raw.baliegdeh };
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
break;
}
}
}
};
for (int i = 0; i < buttonIds.length; i++) {
ImageButton soundButton = (ImageButton) getView().findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The statement is unreachable because you unconditionally return before it can be reached. The fix is simple: move return rootView to the end of the method and instead of getView() use rootView.
Related
I'm creating a soundboard android app that will use multiple fragments to display buttons that when clicked will play a sound. The code I have so far uses two instances of MediaPlayer. I have no idea how to use a single instance of MediaPlayer while still having two fragments.
Here is my code:
package com.davidreadiii.android.soundboardexample1;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.io.IOException;
public class MainFragment {
public static class Fragment1 extends Fragment {
int selectedSoundId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page1, container, false);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
final int[] buttonIds = { R.id.btn1, R.id.btn2, R.id.btn3 };
final int[] soundIds = {R.raw.giggity_giggity_goo, R.raw.hey_baby, R.raw.hump_day };
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
break;
}
}
}
};
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) rootView.findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
return rootView;
}
}
public static class Fragment2 extends Fragment {
int selectedSoundId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.page2, container, false);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
final int[] buttonIds = { R.id.btn4, R.id.btn5, R.id.btn6 };
final int[] soundIds = { R.raw.ios_note, R.raw.old_spice, R.raw.you_suck };
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.start();
break;
}
}
}
};
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) rootView.findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
return rootView;
}
}
}
To my knowledge, I might need to change the fragments to public classes instead of public static classes. Could someone help me find a solution??? Thank you.
You can use the Singleton Pattern:
public class Singleton {
private static Singleton mInstance = null;
private String mString;
private Singleton(){
mString = "Hello";
}
public static Singleton getInstance(){
if(mInstance == null)
{
mInstance = new Singleton();
}
return mInstance;
}
public String getString(){
return this.mString;
}
public void setString(String value){
mString = value;
}
}
Use this pattern for your MediaPlayer, and call getInstance() whenever you need your MediaPlayer instance.
I have an onClick method of a checkbox in a class that extends baseAdapter here:
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = mContext.getApplicationContext().openFileOutput("BitmapImage", Context.MODE_PRIVATE);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "the icon(s) have been saved");
out.close();
// Load back the image file to confirm it works
// Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
// ImageView imageV = (ImageView)findViewById(R.id.);
// imageV.setImageBitmap(bitmap);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
// Intent intent = new Intent (v.getContext(), Drag_and_Drop_App.class);
// v.getContext().startActivity(intent);
// Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
} else {
System.out.println("Un-Checked");
}
}
From what I've seen, I would need an intent from this activity to my other class where I get the created bitmap made in the onClick method above. The issue is that my other class also extends baseadapter so I can't use startActivity().
Here is where I get the bitmap from storage (in other class):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
try {
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = Context.openFileInput("BitmapImage");
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// getThumbnail();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
How can I make it so that I can send intent to my other class so I can get the bitmap?
ADDED:
Does this work the same way? (Please check my coding)
Intent intent = new Intent (v.getContext(), GVABackup.class);
v.getContext().startActivity(intent);
Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
for one class and then
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
Intent intent = new Intent (view.getContext(), GVABackup.class);
view.getContext().startActivity(intent);
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
in my adapter with the GVABackup class like this:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GVABackup extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
ImageView view = (ImageView)findViewById(R.id.layout1);
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = null;
try {
in = openFileInput("BitmapImage");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
I don't fully understand what you are asking but would the LocalBroadcastmanager do what you need?
http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
can someone help me with this. i'm doing a project in which user can watch video and i use surface view, and media player.. Now, i want to have a small screen that plays a video and continues playing on the big screen.. what i have in my code now, is i have two different surface view on the same activity when i click play button it plays video but when i click full screen it does'nt continue playing, its just play the video from the start.
public class MainActivity extends Activity implements OnClickListener ,
SurfaceHolder.Callback{
//For surface
MediaPlayer mediaPlayer, mediaPlayer_fullscreen;
SurfaceView surfaceView, surfaceView_fullscreen;
SurfaceHolder surfaceHolder, surfaceholder_fullscreen;
boolean pausing = false;
boolean pausing_2 = false;
boolean reset = false;
public static int media_length;
//FULL SCREEN
Button play, pause;
ImageButton mExit, resume;
public static int mediaPlayer_length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//For Surface
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setFixedSize(176, 144);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer = new MediaPlayer();
//FULLSCREEN
//For Surface
surfaceView_fullscreen =
(SurfaceView)findViewById(R.id.surfaceView2);
surfaceholder_fullscreen = surfaceView_fullscreen.getHolder();
surfaceholder_fullscreen.addCallback(this);
surfaceholder_fullscreen.setFixedSize(300, 300);
surfaceholder_fullscreen.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mediaPlayer_fullscreen = new MediaPlayer();
media_length = mediaPlayer.getCurrentPosition();
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.play:
playvideo();
break;
case R.id.view_fullscreen:
mediaPlayer.release();
linearlayout_head.setVisibility(View.GONE);
linearlayout_fullscreen.setVisibility(View.VISIBLE);
playvideo_fullscreen();
break;
}
public void playvideo() {
path_path = EditText_path.getText().toString();
pausing = false;
//reset = false;
if(mediaPlayer.isPlaying()){
mediaPlayer.reset();
}
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDisplay(surfaceHolder);
try {
mediaPlayer.setDataSource(getDataSource(path_path));
Log.d("LOGPLAY", path_path);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.start();
//mediaPlayer.pause();
//media_length = mediaPlayer.getCurrentPosition();
}
public void playvideo_fullscreen() {
pausing_2 = false;
//reset = false;
if(mediaPlayer_fullscreen.isPlaying()){
mediaPlayer_fullscreen.reset();
//mediaPlayer_fullscreen.seekTo(media_length);
}
mediaPlayer_fullscreen.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer_fullscreen.setDisplay(surfaceholder_fullscreen);
try {
mediaPlayer_fullscreen.setDataSource(getDataSource(path_path));
Log.d("LOGPLAYFullscreen", path_path);
mediaPlayer_fullscreen.prepare();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//mediaPlayer_fullscreen.start();
mediaPlayer_fullscreen.seekTo(media_length);
}
can someone help me with this please. Thank you.
When you switch between two views media player will not resume where you are paused. So you must do it manual. You will get the current time of video using
MediaPlayer mp=new MediaPlayer();
int currentTime=mp.getCurrentPosition();
After switching the view just seek the video to the 'currentTime'.
mp.seekTo(currentTime);
How do I modify this so that if one sound is playing already and another is clicked on, the previous stops playing and the newly selected starts? Thanks everyone for their help in advance. (this is not all the code just the most important)
public class newBoard extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
Toast.makeText(this, "Thank you for using this App.", Toast.LENGTH_LONG).show();
// ads - load request to display
AdView layout = (AdView)this.findViewById(R.id.adView);
// ads - load display with an ad
AdRequest adRequest = new AdRequest();
adRequest.setTesting(true);
layout.loadAd(adRequest);
// import sound files
final MediaPlayer sound01 = MediaPlayer.create(this, R.raw.sound01);
final MediaPlayer sound02 = MediaPlayer.create(this, R.raw.sound02);
final MediaPlayer sound03 = MediaPlayer.create(this, R.raw.sound03);
final MediaPlayer sound04 = MediaPlayer.create(this, R.raw.sound04);
final MediaPlayer sound05 = MediaPlayer.create(this, R.raw.sound05);
final MediaPlayer sound06 = MediaPlayer.create(this, R.raw.sound06);
final MediaPlayer sound07 = MediaPlayer.create(this, R.raw.sound07);
final MediaPlayer sound08 = MediaPlayer.create(this, R.raw.sound08);
final MediaPlayer sound09 = MediaPlayer.create(this, R.raw.sound09);
final MediaPlayer sound10 = MediaPlayer.create(this, R.raw.sound10);
final MediaPlayer sound11 = MediaPlayer.create(this, R.raw.sound11);
final MediaPlayer sound12 = MediaPlayer.create(this, R.raw.sound12);
final MediaPlayer sound13 = MediaPlayer.create(this, R.raw.sound13);
final MediaPlayer sound14 = MediaPlayer.create(this, R.raw.sound14);
final MediaPlayer sound15 = MediaPlayer.create(this, R.raw.sound15);
final MediaPlayer sound16 = MediaPlayer.create(this, R.raw.sound16);
final MediaPlayer sound17 = MediaPlayer.create(this, R.raw.sound17);
final MediaPlayer sound18 = MediaPlayer.create(this, R.raw.sound18);
final MediaPlayer sound19 = MediaPlayer.create(this, R.raw.sound19);
final MediaPlayer sound20 = MediaPlayer.create(this, R.raw.sound20);
final MediaPlayer sound21 = MediaPlayer.create(this, R.raw.sound21);
final MediaPlayer sound22 = MediaPlayer.create(this, R.raw.sound22);
final MediaPlayer sound23 = MediaPlayer.create(this, R.raw.sound23);
final MediaPlayer sound24 = MediaPlayer.create(this, R.raw.sound24);
final MediaPlayer sound25 = MediaPlayer.create(this, R.raw.sound25);
// play sound files on clicks
Button s01 = (Button) findViewById(R.id.button01);
s01.setText(this.getString(R.string.quote01));
s01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound01.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound01.start();
}
});
registerForContextMenu(s01);
Button s02 = (Button) findViewById(R.id.button02);
s02.setText(this.getString(R.string.quote02));
s02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound02.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound02.start();
}
});
registerForContextMenu(s02);
Button s03 = (Button) findViewById(R.id.button03);
s03.setText(this.getString(R.string.quote03));
s03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound03.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound03.start();
}
});
registerForContextMenu(s03);
Button s04 = (Button) findViewById(R.id.button04);
s04.setText(this.getString(R.string.quote04));
s04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound04.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound04.start();
}
});
registerForContextMenu(s04);
Button s05 = (Button) findViewById(R.id.button05);
s05.setText(this.getString(R.string.quote05));
s05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound05.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound05.start();
}
});
registerForContextMenu(s05);
Button s06 = (Button) findViewById(R.id.button06);
s06.setText(this.getString(R.string.quote06));
s06.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
sound06.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sound06.start();
}
});
registerForContextMenu(s06);
Use a object member variable to hold on to your currently playing sound so that you can call stop() and don't forget to null check it. Don't forget to release() your MediaPlayer object once you leave your activity.
The following is probably a better design: move all your audio files to your assets directory and put the file name in the button's tag, use the same click event handler to get the state of the one MediaPlayer object, stop it if its currently playing, set the new file to play from the button's tag and play the file. This will reduce your duplicate code significantly.
Use a single MediaPlayer instance. Yours is going to fail on most devices as it is anyway for allocating to many instances of MediaPlayer. Also, repetitious code is bad. Bad bad:
public class NewBoard extends Activity {
private MediaPlayer player;
private Resources res;
private int buttonIds = { R.id.button01, R.id.button02, R.id.button03,
R.id.button04, R.id.button05, R.id.button06,
R.id.button07, R.id.button08, R.id.button09,
R.id.button10, R.id.button11, R.id.button12,
R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17,
R.id.button18, R.id.button19, R.id.button20,
R.id.button21, R.id.button22, R.id.button23,
R.id.button24, R.id.button25 };
private int soundIds = { R.raw.sound01, R.raw.sound02, R.raw.sound03,
R.raw.sound04, R.raw.sound05, R.raw.sound06,
R.raw.sound07, R.raw.sound08, R.raw.sound09,
R.raw.sound10, R.raw.sound11, R.raw.sound12,
R.raw.sound13, R.raw.sound14, R.raw.sound15,
R.raw.sound16, R.raw.sound16, R.raw.sound17,
R.raw.sound18, R.raw.sound19, R.raw.sound20,
R.raw.sound21, R.raw.sound22, R.raw.sound23,
R.raw.sound24, R.raw.sound25 };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//Kill this with fire -- just an unnecessary user annoyance.
Toast.makeText(this,
"Thank you for using this App.", Toast.LENGTH_LONG).show();
AdView layout = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest();
adRequest.setTesting(true);
layout.loadAd(adRequest);
player = new MediaPlayer();
res = getResources();
for(int i = 0, n = buttonIds.length(); i < n; i++) {
Button button = (Button)findViewById(buttonIds[i]);
button.setOnClickListener(new SoundClickListener(soundIds[i]));
}
}
private class SoundClickListener implements OnClickListener {
private int id;
public SoundClickListener(int soundId) {
id = soundId;
}
public void onClick(View v) {
player.reset();
player.setDataSource(
res.openRawResourceFd(id).getFileDescriptor());
player.prepare();
player.start();
}
}
}
Something like this. May or may not compile as is. Also, as commented, kill the Toast with fire -- that's just annoying.
I'm creating a soundboard.
When I click on a button, the soundfile is played and selectedSoundId is defined with soundIds[i];
If I long press the button, before button is "short" pressed, the selectedSoundId is not defined.
So I need to define it, even if I didn't "shortpress" the button.
I figured out I've to define it after "onCreateContextMenu", but how?
public class Activity2 extends TabActivity {
/** Called when the activity is first created. */
int selectedSoundId;
int random = (int)Math.ceil(Math.random()*100);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
//Look up the AdView as a resource and load a request.
AdView adView = (AdView)this.findViewById(R.id.adView);
adView.loadAd(new AdRequest());
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("text1").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("text2").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab3").setIndicator("text3").setContent(R.id.tab3));
mTabHost.addTab(mTabHost.newTabSpec("tab4").setIndicator("text4").setContent(R.id.tab4));
mTabHost.setCurrentTab(0);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
//just keep them in the same order,
final int[] buttonIds = { R.id.button1, R.id.button2,};
final int[] soundIds = { R.raw.sound1, R.raw.sound2, };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
//find the index that matches the button's ID, and then reset
//the MediaPlayer instance, set the data source to the corresponding
//sound effect, prepare it, and start it playing.
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
//set the same listener for every button ID, no need
//to keep a reference to every button
for(int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button)findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Save as...");
menu.add(0, v.getId(), 0, "Ringtone");
menu.add(0, v.getId(), 0, "Notification");
// How do I give SelectedsoundId here the value of soundIds[i]
//Like : selectedSoundId = soundIds[i];
}
UPDATE
I added this code in the OnCreateContextMenu and I think it's working correctly now.
I'm not sure if v.getId(); is necessary?
v.getId();
for(int i = 0; i < buttonIds.length; i++) {
if(v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
}
}
The onCreateContextMenu() method has a parameter named View v that represent the View for which the ContextMenu is being built. So from this you could get the ID (v.getId()) and then, like you did in the View.OnClickListener listener, find out the position in the buttonIds array and then set the selectedSoundId accordingly.
Also this:
menu.add(0, v.getId(), 0, "Ringtone");
should be something like this:
menu.add(Menu.NONE, UNIQUE_ID, Menu.NONE, "Ringtone");
Edit:
In the code you added i see the line v.getId(); before your for loop, that isn't necessary.
Regarding my menu edit you should assign a unique ID for your menu item so in the method onContextItemSelected() you can find out which menu item the user pick(see this class as an example). In the other fields you could use 0 or Menu.NONE.