0

I need to change the value of an element from a different thread

The error is on function gameButton.setText(String.valueOf(out));, I am aware I am not allowed to change main UI elements from external threads.

What is the least complicated way to change the value of this element from an external thread?

 public class MainActivity extends Activity {

    DFT sProc = new DFT();
    Button gameButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        RelativeLayout gameLayout = new RelativeLayout(this);
        gameButton = new Button(this);

        //Add the start Button
        gameButton.setText("Start");
        gameButton.setBackgroundColor(Color.MAGENTA);
        gameLayout.setBackgroundColor(Color.LTGRAY);
        RelativeLayout.LayoutParams buttonDetails = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT
        );
        buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
        buttonDetails.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        gameLayout.addView(gameButton, buttonDetails);
        setContentView(gameLayout);

        final Thread t = new Thread(this::soundThread);
        t.start();
    }

    private void soundThread(){
        for(ini i = 0; i < 100; i++)
        {
            sProc.start(this);
            try {
                Thread.sleep(1000);
                double out = sProc.getAmplitude();
                gameButton.setText(String.valueOf(out));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            sProc.stop();
        };
    }
}
Mich
  • 3,188
  • 4
  • 37
  • 85

0 Answers0