Search code examples
javaandroidandroid-mediaplayertextviewandroid-button

Change action of a button according to text displayed



I would like to know how to change the action of a button according to what text is display in a TextView. I am using Android Studio.

I have tried to use an 'if statement' but that doesn't seem to work. So, I want a different sound to play according yo what text is displayed in the TextView.

package com.msp.exampleapplication;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class PrimaryClass extends AppCompatActivity {

    TextView placeholder;
    Button playsound_button;
    MediaPlayer mySound;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.primary_layout);

        placeholder = (TextView) findViewById(R.id.placeholder);
        playsound_button = (Button) findViewById(R.id.playsound_button);

        placeholder.setText(getIntent().getStringExtra("message"));

        }

    public void playSound(View view) {

        if (placeholder.equals("BMW M4")) {

            mySound = MediaPlayer.create(this, R.raw.sound);
            mySound.start();
        }

        else if (placeholder.equals("BMW M5")) {

            mySound = MediaPlayer.create(this, R.raw.sound2);
            mySound.start();
        }
    }
}

So, if the text of the TextView (placeholder) is "BMW M4", then when the button is clicked, it must play R.raw.sound. And if "BMW M5" is displayed in the TextView (placeholder), then R.id.sound2 must play.
But as I said, I've attempted to use the if statement and when I click the button, no sound plays at all.


Solution

  • Yes, as @Akshay Bhat 'AB' said, you must do this:

       if (placeholder.getText().toString().equals("BMW M4")) {
    
            mySound = MediaPlayer.create(this, R.raw.sound);
            mySound.start();
        }
    
        else if (placeholder.getText().toString().equals("BMW M5")) {
    
            mySound = MediaPlayer.create(this, R.raw.sound2);
            mySound.start();
    
        }
    

    Refer this post: how to get text from textview There's one error in the comment tho, its toString() and not toString