Here is a quick show of the issue with my current code. It is created in Android Studio:
public class OptionActivity extends Activity {
Spinner spnr;
int songs[] = new int[] {R.raw.sound1,R.raw.sound1,R.raw.sound3,R.raw.sound4};
MediaPlayer myMediaPlayer;
int current_index = 0;
String[] mySelectSounds = {
"Robot",
"Manly man",
"Woman",
"Cat",
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_option);
myMediaPlayer = MediaPlayer.create(this, songs[0]);
spnr = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, mySelectSounds);
spnr.setAdapter(adapter);
spnr.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int position = spnr.getSelectedItemPosition();
Toast.makeText(getApplicationContext(), "You have selected " + mySelectSounds[+position], Toast.LENGTH_LONG).show();
current_index = (current_index + position);
if (position == 3) {
myMediaPlayer.start();
//What to put here, to make it change the array number in myMediaPlayer = MediaPlayer.create(this, songs[0]);?
}}
I have 4 arrays, which are supposed to be sounds. I want to be able to change which sound is used in the different positions of the dropdown menu/spinner through an array.
My issue is, when I create the myMediaPlayer in the OnCreate, I don't know how to change it. The int current_index is set to be the same as the position of the spinner, so I want to add that to the array's position, according to the menu number in my spinner. I have tried my own hand with it, but I'm fairly inexperienced with android studio, and the sample I have found, used the code
if (position == 3) {
getResources().openRawResourceFd(songs[current_index]);
myMediaPlayer.start();
}
which, according to the other questions asked here seems to work, but it is not working for me.
You need to create a new MediaPlayer like this in your item click
MediaPlayer mp = MediaPlayer.create(OptionActivity.this, songs[current_index]);
Try
current_index = position;
if (current_index == 3) {
myMediaPlayer.start();
myMediaPlayer = MediaPlayer.create(this, songs[current_index]);
}}
Related
I got a problem with playing two MediaPlayers simultaneously.
In my code I made a spinner to let the user to choose his first song and then the second song, at the moment that the user chooses the first song it starts to play and when the user choose the second song it will play with the first one.
But the problem is that, when the user chse the second song it stops the first one...
What can I do to fix it?
Ty!
The code:
public void setSpinner() {
Spinner spine = (Spinner) findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.song, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spine.setAdapter(adapter);
final MediaPlayer mp1 = new MediaPlayer();
spine.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String st = parent.getItemAtPosition(position).toString();
if (st.equals("First Song")) {
setMedia1(mp1);
mp1.start();
}
if (st.equals("Second Song")) {
setMedia2(mp1);
mp1.start();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void setMedia1(MediaPlayer mp2) {
Bundle b1=getIntent().getExtras();
float s = b1.getFloat("speed");
Bundle b2=getIntent().getExtras();
float v = b2.getFloat("volume");
try {
String s1 = getIntent().getStringExtra("song1");
final Uri uri1 = Uri.parse(s1);
mp2.setDataSource(getApplicationContext(), uri1);
mp2.prepare();
mp2.setVolume(v,v);
mp2.setPlaybackParams(mp2.getPlaybackParams().setSpeed(s));
} catch (Exception e) {
}
}
public void setMedia2(MediaPlayer mp2) {
Bundle b3 = getIntent().getExtras();
float sp1 = b3.getFloat("speed1");
Bundle b4 = getIntent().getExtras();
float vo1 = b4.getFloat("volume1");
try {
String s2 = getIntent().getStringExtra("song3");
final Uri uri2 = Uri.parse(s2);
mp2.setDataSource(getApplicationContext(), uri2);
mp2.prepare();
mp2.setVolume(vo1, vo1);
mp2.setPlaybackParams(mp2.getPlaybackParams().setSpeed(sp1));
} catch (Exception e) {
}
}
try SoundPool,its a better method of dealing with multiple audio files at the same time.
Heres the documentation:
http://developer.android.com/reference/android/media/SoundPool.html
Heres the example:
http://examples.javacodegeeks.com/android/android-soundpool-example
Hope this helps
Reference
Try using two MediaPlayer instances. Change your setSpinner method to do something like:
public void setSpinner() {
Spinner spine = (Spinner)findViewById(R.id.spinner3);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.song, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spine.setAdapter(adapter);
// You were only creating a single MediaPlayer instance in your version...
final MediaPlayer mpA = new MediaPlayer();
final MediaPlayer mpB = new MediaPlayer();
spine.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String st = parent.getItemAtPosition(position).toString();
if (st.equals("First Song")) {
// Use mpA for the first song
setMedia1(mpA);
mpA.start();
}
else if (st.equals("Second Song")) {
// Use mpB for the second song
setMedia2(mpB);
mpB.start();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I do not know if that will get the exact behavior you are looking for, but it stands a better chance at playing two songs simultaneously than using a single MediaPlayer instance.
I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...
In my activity i have two spinners, one image view and two buttons.
depending on first spinner the second spinners should change. and while selecting birds in first spinner the second spinner should show parrot peacock etc. while selecting parrot in second spinner i should get the image of parrot.
till this i am getting.
but now what i want is while i press a button then i should get the voice of parrot.
in this code when i am pressing the button i am getting the same voice for every picture change in second spinner
public class MainActivity extends Activity {
ImageView displayIV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
;
Button b1;
b1=(Button)findViewById(R.id.button1);
Spinner friend = (Spinner) findViewById(R.id.spinner1);
final Spinner subFriend = (Spinner) findViewById(R.id.spinner2);
displayIV=(ImageView)findViewById(R.id.imageView1);
final ArrayList<String> friend_options = new ArrayList<String>();
final ArrayList<String> subfriend_options = new ArrayList<String>();
friend_options.add("Nuz");
friend_options.add("Dur");
friend_options.add("Tara");
friend_options.add("Sama");
ArrayAdapter<String> friendAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_spinner_item,
friend_options);
friend.setAdapter(friendAdapter);
ArrayAdapter<String> subFriendAdapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_spinner_item,subfriend_options);
subFriend.setAdapter(subFriendAdapter);
friend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
String friendName =
friend_options.get(position).toString();
resetFriend(friendName);
// subFriend.setAdapter(null);
}
private void resetFriend(String friendName) {
subfriend_options.removeAll(subfriend_options);
if (friendName.equals("Nuz")) {
subfriend_options.add("Nuz_1");
subfriend_options.add("Nuz_2");
subfriend_options.add("Nuz_3");
subfriend_options.add("Nuz_4");
} else if (friendName.equals("Dur")) {
subfriend_options.add("Dur_1");
subfriend_options.add("Dur_2");
subfriend_options.add("Dur_3");
subfriend_options.add("Dur_4");
} else if (friendName.equals("Tara")) {
subfriend_options.add("Tara_1");
subfriend_options.add("Tara_2");
subfriend_options.add("Tara_3");
subfriend_options.add("Tara_4");
} else {
subfriend_options.add("Sama_1");
subfriend_options.add("Sama_2");
subfriend_options.add("Sama_3");
subfriend_options.add("Sama_4");
}
ArrayAdapter<String> subFriendAdapter = new
ArrayAdapter<String>( getApplicationContext(),
android.R.layout.simple_spinner_item,
subfriend_options);
subFriend.setAdapter(subFriendAdapter);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
subFriend.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
arg0.getItemAtPosition(arg2);
final ImageView im =
(ImageView)findViewById(R.id.imageView1);
String s=((TextView)arg1).getText().toString();
if(s.equals("Tara_1")){
im.setImageDrawable(getResources().getDrawable(R.drawable.crow));
}
if(s.equals("Tara_2"))
im.setImageDrawable(getResources().getDrawable(R.drawable.india1));
if(s.equals("Tara_3"))
im.setImageDrawable(getResources().getDrawable(R.drawable.peacock));
if(s.equals("Tara_4"))
im.setImageDrawable(getResources().getDrawable(R.drawable.robin1));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MediaPlayer mMediaPlayer = MediaPlayer.create(this,
R.raw.Kalimba);
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.abc);
mp.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
In the setOnClickListener method of your button, b1, you need to know which image has been selected on the spinner (your description is a little bit confusing so i don't have clear exactly which spinner is going to change the sound that you app has to reproduce).
Anyway, let think that the spinner is "friend_options".
In you setOnClickListener we have to know which item has been selected for the user when click on the button, right? And depending of which item was selected, we will play one specific sound.
So....
Another important poin is that you should create the variable of the mediaplayer outside of the onclickListener, like a class variable:
//Class variable:
public MediaPlayer mp;
In the onCreate method you should initialize the MediaPlayer component:
public void onCreate()
{
MediaPlayer.create(MainActivity.this, R.raw.abc); //Default sound, it is not
//importat because we are going
//to chain the value of the
//file to reproduce in the next
//step.
}
b1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Here we are going to take the item selected:
String itemSelected = spinner.getSelectedItem().toString();
int soundToPlayId=0;
if(itemSelected.equals("Nuz"))
{
soundToPlayId = R.raw.Kalimba ;
}
else if(itemSelected.equals("Dur"))
{
soundToPlayId = R.raw.abc;
}
// etc etc etc --> you should put all the sound associated to all the
// friends
//And now you only have to reproduce if the item was selected properly:
if(soundToPlayId !=0) //if the id is different to 0:
{
mp = MediaPlayer.setDataSource(MainActivity.this, soundToPlayId);
mp.start();
}
}
});
Let see if it is working!!! Ask me if you have any doubt...and if the answer is correct, vote me and check as correct!!! (I need points, thanks!)
I have tried Googling but couldn't get an answer specific to my problem.
I am trying to launch an activity when a item is clicked. The code is below:
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_of_circuits);
raceTrackList = getResources().getStringArray(R.array.tracklist_array);
Spinner s1 = (Spinner) findViewById(R.id.circuitListSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, raceTrackList);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
However at the moment it loads straight into the activity at the top of the list (TopGear). How do you get around this so that a user can see the list and select it i.e. not start an intent immediately - use an if statement?
Thanks.
This happens because the method is called the first time the Activity loads. There should be a better way to handle this but you could simply set a boolean flag
public class ListOfCircuits extends Activity
{
String[] raceTrackList;
boolean go = false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
then set it to true the first time it is called and check it there
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if (go)
{
// your code
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
else
{ go = true; }
}
CodeMagic think I have it working like a boss now:
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3)
{
if(go)
{
int index = arg0.getSelectedItemPosition();
if(index == 0)
{
Toast.makeText(getBaseContext(),
"Please select a race crcuit.",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(),
"You have selected: " + raceTrackList[index],
Toast.LENGTH_SHORT).show();
String intentString;
String circuitChosen = raceTrackList[index].toString();
intentString = ("net.learn2develop." + circuitChosen);
startActivity(new Intent(intentString));
}
}
else
{
go = true;
}
}
I only load Intents that I want (race circuits) and if a user selects "Choose from below:" only one relevant Toast gets displayed.
Thanks.
The answer to my answer was:
Add the Boolean as codeMagic suggested and amend my array to:
<string-array name="tracklist_array">
<item>Choose from below:</item>
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
From
<string-array name="tracklist_array">
<item>TopGear</item>
<item>Snetterton</item>
<item>Silverstone</item>
<item>Donnington</item>
</string-array>
And the final code is for Java - see below.
Thanks again.
I'm trying to pass a value from an android spinner selection into a url. All of my other vars are passing and the toast on the spinner in displaying the correct spinner choice when selected. (for purposes here, the code doesn't show all vars.)
My log shows the country VAR as NULL. Need to get the "country0" value to pass like the others. How can I make this happen?
thanks
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(DEBUG_TAG, "onCreate");
mContext = this; //TODO legacy may not be needed
SERVER = this.getString(R.string.mygallerist_server_base);
settings = getSharedPreferences(PREFS_NAME, 0);
uid = settings.getString("uid", NOT_SET);
//SPINNER
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.countries_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
mOver35CheckBox = (CheckBox) findViewById(R.id.Over35);
class MyOnItemSelectedListener implements OnItemSelectedListener {
//SPINNER PARSING
#Override
public void onItemSelected(AdapterView<?> country0,
View view, int pos, long id) {
Toast.makeText(country0.getContext(), "The country is " +
country0.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView country0 ) {
// Do nothing.
}
}
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
final String country = country0;///MAYBE THIS IS WHAT IS WRONG
setPassword.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// If all fields filled in then go to server
String country1 = country; /// OR MAYBE THIS IS WHAT IS WRONG
String userName = mUserNameEditText.getText().toString();
Perhaps I'm missing something in your question, but when you select the value for the Toast, you could just set the value of a private member, then read this value in your onClick, (being as you know you're getting the correct value in the onItemSelected)
private String countrySelection;
public void onItemSelected(AdapterView<?> country0, View view, int pos, long id) {
countrySelection = country0.getItemAtPosition(pos).toString();
Toast.makeText(country0.getContext(), "The country is " + countrySelection, Toast.LENGTH_LONG).show();
}
...
final String country = countrySelection;
setPassword.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
sendDataToServer(country, ...);
Does this solve your issue?
Edit...
What type is country0 in this context? (I don't have comment privileges yet)
final String country = country0;///MAYBE THIS IS WHAT IS WRONG