Search code examples
androidforceclose

mediaplayer not working properly


I have a problem trying to force close in my application. Below is my code for playing sound when a button is clicked. Can any body explain to me how to avoid the problem I am having?

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;

public class Click extends Activity
 {
  MediaPlayer mp1;

  @Override
    public void onCreate(Bundle savedInstanceState)
     {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_click);

      mp1 = MediaPlayer.create(this, R.raw.sound1);
      final Button button1 = (Button) findViewById(R.id.button1);
      button1.setOnClickListener((OnClickListener) this);
    }

   public void onClick(View v) 
     {
      switch(v.getId()) 
       {
        case R.id.button1:
        mp1.start();
        break;
       }
     } 
    }

Solution

  • Your first problem has to do with the fact that you did not implement OnClickListener and instead casted your Click class into an OnClickListener.

    Modify your code as follows:

    First the class declaration:

    public class Click extends Activity implements OnClickListener
    

    Then change

     button1.setOnClickListener((OnClickListener) this);
    

    to just

    button1.setOnClickListener(this);