0

I'm creating a button to stop a light sensor after grabbing two equal light values for a duration of 2 seconds using the handler's delay function. It works fine at first but when I press the button again, the delay seems to get shorter and shorter, and eventually doesn't happen at all.

stateLx.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        onResume();
        stateLx.setEnabled(false);
        doub2x.setText(Double.toString(0));
        doub1x.setText(Double.toString(0));

        //Stabilization Handlers
        m_handler = new Handler();
        m_handlerTask = new Runnable() {
            public void run() {

                doub1 = movingValue[0];
                doub1x.setText(Double.toString(doub1));
                m_handler.postDelayed(this, 1000);

            }
        };

        m2_handler = new Handler();
        m2_handlerTask = new Runnable() {
            public void run() {

                doub2 = movingValue[0];
                doub2x.setText(Double.toString(doub2));
                m2_handler.postDelayed(this, 2000);

                if (doub1 != doub2) {
                    instructions.setText("unequal");
                } else {
                    instructions.setText("equal");
                    getInitialLightValue();
                    reCalculateInitial();
                    beerLambert(volValues, lxValuesNew);

                }

            }
        };

        //Handlers for stabilizer
        m_handler.postDelayed(m_handlerTask, 1000);
        m2_handler.postDelayed(m2_handlerTask, 3000);
        lame.setText(Double.toString(absorbValues[0]));
        stateLx.setEnabled(true);


    }

});

I've tried putting the handlers both in and out of the onclick function, as well as including the onResume() function at the beginning of the button press, but I'm having no luck. Is there something wrong with my code?

Genevieve
  • 975
  • 2
  • 21
  • 35

1 Answers1

1

You keep recreating your Handlers and Runnables. This is part of the problem, you should check to see if you are already polling before starting again.

Also, this is a side note -- but it's odd to call lifecycle methods, like onResume() yourself, since it calls up to the super.

Submersed
  • 8,810
  • 2
  • 30
  • 38
  • Thank you! I fixed it using https://stackoverflow.com/questions/5883635/how-to-remove-all-callbacks-from-a-handler – Genevieve Feb 05 '18 at 03:50