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.
Related
I am trying to create a search view in the action bar of my app, which will perform search (that is will display the names of items from the listview according to the letter typed) over a listview in the app. Listview uses a listadapter class. When I enter text in the search view, nothing happens. I am quite new with search view, tried to use the codes got from the net but that didn't help. :( Can you please suggest me over how to do this? Should I create another class for it?
Here is my code:
ListAdapter.java
public class ListAdapter extends BaseAdapter{
Vector listData = null;
public void setData(Vector data) {
listData = data;
}
private Context _context;
private List<String> list;
ViewHolder holder=null;
View row=null;
public ListAdapter(Context _context,List<String> list)
{
this._context=_context;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
private static class ViewHolder
{
public TextView textView;
public ViewHolder(View row) {
// TODO Auto-generated constructor stub
textView = (TextView) row.findViewById(R.id.rowTextView);
}
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
row=convertView;
holder=null;
try{
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
holder=new ViewHolder(row);
row.setTag(holder);
Log.d("newrow", "New row");
/*/View row = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
}
TextView textView = (TextView) row.findViewById(R.id.rowTextView);*/
holder.textView.setText(list.get(position).toString());
}
else
{
holder= (ViewHolder) row.getTag();
Log.d("recycle", "Recycling stuff");
}
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
if(row!=null)
{
if(position==MainActivity.selected_item)
{
row.setBackgroundColor(Color.RED);
}
else
{
row.setBackgroundColor(Color.BLACK);
}
}
}
catch(Exception e)
{
}
return row;
}
public Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> adapter ;
ListAdapter listAdapter;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song,title;
int index,current_position;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp,mp2;
ActionBar bar;
private Boolean state=false;
private static int save = -1;
int count=0;
private static final String TAG = MainActivity.class.getSimpleName();
private Context _context = this;
public static int selected_item=-1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp2 = new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
_context=this;
adapter = new ArrayAdapter<String>(_context,R.layout.simplerow, listSoundNames);
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
EditText editText = new EditText(getApplicationContext());
getActionBar().setCustomView(editText);
//bar.setDisplayShowTitleEnabled(true);
//bar.setDisplayHomeAsUpEnabled(true);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
//listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listSoundNames);
listAdapter=new ListAdapter(_context,listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//////////////////changing list item background on click///////////////////
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
String selected = listTest.get(position);
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
//bar.setTitle(title);
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
index = position;
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.stop();
mp.reset();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
}
else
{
index = (list.getAdapter().getCount()-1)-1;
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
if (v.equals(next))
{
mp.stop();
mp.reset();
index = index +1;
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
mp.setDataSource(getApplicationContext(), uri);//setting new data source
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();//PROBLEM: NOT PLAYING
Toast.makeText(MainActivity.this, ""+uri, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
play.setImageResource(R.drawable.play);
}
/*#Override
protected void onStop() {
super.onStop();
mp.stop();
Toast.makeText(getApplicationContext(), "stopped", Toast.LENGTH_LONG).show();
}*/
//////////////////////////////////////////Search box/////////////////////////////////////////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setQueryHint(Html.fromHtml(("<font color = #ffffff>"+"Listen Now"+"</font>")));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener()
{
#Override
public boolean onQueryTextChange(String newText)
{
// this is your adapter that will be filtered
//listAdapter.getFilter().filter(newText);
Toast.makeText(getApplicationContext(), "type"+newText, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public boolean onQueryTextSubmit(String query)
{
// this is your adapter that will be filtered
//((Filterable) listAdapter).getFilter().filter(query);
//listAdapter.getFilter().filter(query);
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
/* try
{
File fl = new File("/sdcard/");
File[] listOfFiles = fl.listFiles();
String selectedPath="";
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.equalsIgnoreCase(query) && s.endsWith(".mp3"))
{
selectedPath= listOfFile.getPath();//not receiving the path:PROBLEM:HOLDING THE POSITION FOR LIST ITEM
//listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
Toast.makeText(getApplicationContext(), listOfFile.getPath(), Toast.LENGTH_SHORT).show();
/*mp.setDataSource(selectedPath);
mp.prepare();
mp.start();
}
/////////////////////////////////
File f = new File("/sdcard/"+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner("/sdcard/"+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }*/
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
Screenshots:
1) In your layout.xml:
<android.support.v7.widget.SearchView
android:id="#+id/mSearchView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:searchIcon="#android:drawable/ic_menu_search"
app:defaultQueryHint="#string/search_hint"/>
2) Declare SearchView searchView; in global scope (outside every function).
3) set the reference of your layout widget searchView = (SearchView) view.findViewById(R.id.mSearchView); in any function/method you like, where you initialize your views.
4) and then add this code in whatever function/method you like :
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// your code when you submit your search
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// your code when you type on your searchview
return true;
}
});
This is how to implement searchView.
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.
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
Every time I click on:
assist_update_btn
I the textview should be update with text from a different string value however it never appears to do anything when I click assist_update_btn.
Any input is greatly appreciated.
SOURCE:
public class UpdateActivity extends Activity implements OnClickListener {
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
public static int count;
AlertDialog mErrorAlert = null;
int version;
public static int TotalSteps = 8;
private TelephonyManager tm;
private static final String LOG_TAG = "STDataSettings";
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
private int mInstructionNumber = 0;
AlertDialog mConfirmAlert = null;
public static InputStream stream = null;
public static XmlParserHandlerFinal handler;
private NetworkTask task;
private AnimationDrawable loadingAnimation;
private static final String TAG = "UpdateActivity";
Context ctx;
private Button assist_update_btn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
handler = new XmlParserHandlerFinal();
int version = android.os.Build.VERSION.SDK_INT;
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo MNC MCC present
else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Initial UI setup for versions lower than ICS
setContentView(R.layout.update);
mUpdateButton = (Button) findViewById(R.id.update_button);
mUpdateButton.setOnClickListener(this);
} else {// ICS and up
// task.execute();
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
task = new NetworkTask();
task.execute("");
// Device has T-Mo network SIM card MCC and MNC correctly
// populated
// Reduce number of steps to 6
TotalSteps = 6;
}
}
}
public void onClick(View v) {
if (v.equals(assist_update_btn)) {
// Update button for versions lower than ICS is selected
// setContentView(R.layout.updating);
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
// finish();
} else if (v.getId() == R.id.assist_update_btn) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
//finish();
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
// AsyncTask to call web service
class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected InputStream doInBackground(String... params) {
try {
// saving the response in InputStream
stream = getQueryResults("https://dl.dropboxusercontent.com/u/31771876/GetPhoneSettings-ST-rsp-eng.xml");
// stream = new BufferedInputStream(https.getInputStream());
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) { // Print the content on the console
System.out.println (strLine);
System.out.println (strLine);
in.close();
}
} catch (IOException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SAXException e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
e.printStackTrace();
}
// The code below plays a Simple Promo animation
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
}
return stream;
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
// HttpsURLConnection https = null;
HttpsURLConnection https = null;
String uri = urlQueryString;
URL urlo = new URL(uri);
try {
https = (HttpsURLConnection) urlo.openConnection();
https.setConnectTimeout(20000); // 20 second timeout
https.setRequestProperty("Connection", "Keep-Alive");
if ("gzip".equals(https.getContentEncoding())) {
stream = new GZIPInputStream(stream);
} else
stream = https.getInputStream();
} catch (SSLException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (SocketTimeoutException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
e.printStackTrace();
} finally {
// https.disconnect();
}
return stream;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2], progress[3], progress[4]);
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the ArrayLists
success();
assistUpdate();
//setContentView(R.layout.assist_update);
}
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener(this);
}
private void setProgressImgView(Integer imageViewId1, Integer imageViewId2, Integer imageViewId3, Integer imageViewId4, Integer imageViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview1.setBackgroundResource(imageViewId1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview1.setBackgroundResource(imageViewId2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview1.setBackgroundResource(imageViewId3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview1.setBackgroundResource(imageViewId4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setBackgroundResource(imageViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(stream);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// to set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
//finish();
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getMmscProxyArr();
portArr = handler.getMmsPortArr();
count = handler.getCount();
//System.out.println("testing123");
for(int i = 0; i < nameArr.size()-1; i++){
System.out.println(nameArr.get(i));
}
for(int i = 0; i < ApnArr.size()-1; i++){
System.out.println(ApnArr.get(i));
}
}
}
Try doing like this
public void onClick(View v) {
if (v.getId() == R.id.assist_update_btn) {
//Your code
}
else if (v.getId() == R.id.assist_instr_btn) {
//Your code
}
}
You are using
if (v == assist_update_btn)
when you should be using
if (v.equals(assist_update_btn)).
I personally think it's more robust to create a separate OnClickListener for each button instead of handling all buttons with one method.
Change:
public void onClick(View v) {
if (v == assist_update_btn) {
to:
public void onClick(View v) {
if (v.getId() == R.id.assist_update_btn) {
and your problem should be long gone.
Initialize TextView in assistUpdate(). Declare tv as a class member.
#Override // missing override annotation
public void onClick(View v) {
switch(v.getId())
{
case R.id.assist_update_btn :
// do something. assist_update_btn click code here
break;
case R.id.mAssistInstrButton :
// do domething . mAssistInstrButton click code here
break;
}
I see you have setContenView twice for the same activitty. I don't think its necessary.
Edit :
You have a for loop in doInbackground() you also call publishProgress more than once and you have multiple try catch block.
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
Log.d(TAG, "sleep failure");
}
I am confused as to what your doing. But i strongly suggest you to rethink your design.
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.