mrbTT mrbTT - 2 months ago 12
Java Question

Android - make a button display a value on screen and playing sound correctly

I'm doing the Udacity's android beginner course (even thou I'm not beginner to programming) and decided to fool around a little.

I've managed to make a button either change the value on screen (by adding +1 value) or to play a sound, but when I mix both, the button only plays the sound, but does not add a number / update the value on screen, anyone knows why?

I have three methods; 1 for calling the mediaPlayer:

// This method calls mediaPlayer
public void mediaPlayer (String sound, String id){
Uri uriPlayer = Uri.parse("android.resource://" + getPackageName() + "/raw/" + sound );
final MediaPlayer mp = MediaPlayer.create(this, uriPlayer);

int playIdInt = getResources().getIdentifier(id, "id", getPackageName());
Button play_button = (Button)this.findViewById(playIdInt);
play_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.start();
}
});
}



  1. For displaying the value on screen


    /**
    * This method displays the given quantity value on the screen.
    */
    private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText("" + number);

  2. For adding +1 value to the variable, calling the display method and the media player method:



public void increment (View view){
quantity = quantity + 1;
display(quantity);
mediaPlayer("mariocoin", "plus_button");
}


EDIT: not sure if needed, but here is XML of the button:

<Button
android:id="@+id/plus_button"
android:layout_width="48dp"
android:layout_height="48dp"
android:onClick="increment"
android:text="+" />


The thing is that when I play the button the first time, it adds 1 and display on the screen, but no sound played. The second and subsequent times it only plays the sound. It does not add +1 to the variable nor change the value on screen. Why and how can I fix this?

Answer

It seems that you have define two ClickListeners for same button. The first one calls increment method and the second one is defined inside media player method. That listener is not required.

//Somewhere in oncreate .. Not required if xml has onclick specified
Button play_button = (Button)this.findViewById(playIdInt);
play_button.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
       increment();
    }
});


public void increment (View view){
       quantity = quantity + 1;
       display(quantity);
       mediaPlayer("mariocoin", "plus_button");
}

// This method calls mediaPlayer
public void mediaPlayer (String sound, String id){
            Uri uriPlayer = Uri.parse("android.resource://" + getPackageName() + "/raw/" + sound );
            final MediaPlayer mp = MediaPlayer.create(this, uriPlayer);
            mp.start();
        }
Comments