Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I created this function to make the button do a sound when i click it, the sound file is mp3 located in raw/button_click.mp3 directory .

fun play_sound(which_one:Int) {
    if(which_one == 1){
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
        mediaPlayer?.start()

But i get the following error when i run it Unresolved reference: Context

How should I edit my code to solve this problem?

By the way just ignore the if statement for now it always turns true for this stage of development.

Unresolved reference: Context

You receive the following error because you are using the Class instead of your variable name as parameter.

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(Context,R.raw.button_click)
        mediaPlayer?.start()

There are also different kind of Contexts in Android.

You have your Application, Activity, and Fragment Context, which is also tied to different lifecycles depending on what Context you used.

If this function is a member of your Activity.

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(this@YourActivityHere,R.raw.button_click)
        mediaPlayer?.start()

Fragment

fun play_sound(which_one:Int) {
    if(which_one == 1) {
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(requireContext(),R.raw.button_click)
        mediaPlayer?.start()

pass proper active Context to this method

fun play_sound(ctx:Context, which_one:Int) {
    if(which_one == 1){
        val mediaPlayer:MediaPlayer? = MediaPlayer.create(ctx, R.raw.button_click)
        mediaPlayer?.start()
                if you start this method from Activity then you may pass this as Activity IS a Context instance (extends it)
– snachmsm
                Nov 5, 2020 at 21:20
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.