Issue
I have this code:
hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
final MediaPlayer mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
mp2.start();
}
public void onNothingSelected(AdapterView<?> parentView) {
}
});
(The code basically runs when a new item is selected of a spinner and then plays a song, which later will be a variable based on what was picked, but I'm fine as it is for now).
Problem: I want to be able to use 'mp2' out of this public void, (I want a button which pauses it). How can I do this?
Solution
Move the variable mp2
to the instance of the parent class. This will keep a running reference to it which you can interact with whenever you please. You will need to remove the final
qualifier though if MediaPlayer.create(...)
will be called more than once and stored.
edit:
I was referring to something along the lines of this:
class SomeClass {
private MediaPlayer mp2 = null;
private void whateverFunctionYouAreIn() {
hubSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
SomeClass.this.mp2 = MediaPlayer.create(Textbox.this, R.raw.hero);
SomeClass.this.mp2.start();
}
public void onNothingSelected(AdapterView<?> parentView) {}
});
//TODO: put this in an onClickListener:
if (this.mp2 != null) {
this.mp2.pause();
}
}
}
Answered By - Jake Wharton
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)