0

I am trying to activate a sound with an switch widget, so I can turn it off as well. Though I also want it to shut down automatically of after a few seconds. everything works though the app crashes on s.performClick(); anyone know how to fix the problem I have?

down here is my full code of the fragment.

public static class Therapy extends Fragment implements CompoundButton.OnCheckedChangeListener{
    MediaPlayer player = null;
    Switch s;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
        View v = inflater.inflate(R.layout.therapy, container, false);           
        Switch s = (Switch)v.findViewById(R.id.switch1);
        s.setOnCheckedChangeListener(this);

        return v;   
    }

    class MyTimerTask extends TimerTask {
        public void run() {
            s.performClick();
        }

    }

    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {                    
                player = MediaPlayer.create(getActivity(), R.raw.bird1);
                player.setLooping(true);
                player.start();

                MyTimerTask myTask = new MyTimerTask();
                Timer myTimer = new Timer();
                myTimer.schedule(myTask, 1000);
            } else {
                player.stop();
                player.release();
            }
        }
Ariel Magbanua
  • 3,083
  • 7
  • 37
  • 48
N. Janné
  • 105
  • 6
  • 1
    What does the logcat say when the app crashes? – CaseyB Mar 08 '13 at 16:23
  • [link picture](http://oi48.tinypic.com/2my1z5u.jpg) that, is the error i get from logcat, now trying it with an Handler and Hanler.postDelayd, still crashes on s.performClick(); – N. Janné Mar 08 '13 at 21:06

1 Answers1

0

Taking a guess here, since I didn't attempt to build your code and run it, but:

s.performClick() is a UI-accessing operation, and cannot be done with a Timer. You might want to consider having the Timer call Handler.post (passing in a Runnable) to make sure your UI-accessing stuff doesn't make Android complain. Alternately, depending on your needs, you could just build a timer entirely with Handler.postDelayed.

Alex
  • 1,103
  • 1
  • 11
  • 24
  • i took your suggestion of using handlers, and in this case it defiantly is more logical to use. i now got this within my "onCheckedChange listener" 'mHandler.removeCallbacks(r); mHandler.postDelayed(r, 5000);' and this within my fragment: ' Runnable r=new Runnable() { public void run() { s.performClick(); } };' it still crashes tho. any idea? – N. Janné Mar 08 '13 at 21:10
  • I just found out my switch objective was also declared in the wrong spot, it works now, thanks allot Alex! – N. Janné Mar 08 '13 at 21:42