-1

MyThread class is used to change the value of the myValue attribute in ActivityTwo Class.

public class MyThread implements Runnable {

    private ActivityTwo activity;

    public MyThread(ActivityTwo activity) {
        this.activity = activity;
    }

    @Override
    public void run() {
          while(true){
            activity.setValue(2);
         }
    }
}

ActivityTwo is an AppCompatActivity activity which runs as the main Thread.

public class ActivityTwo extends AppCompatActivity {

    private MyThread myThread;
    private Button startLogBtn;
    private int myValue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_two);

         startLogBtn = findViewById(R.id.startLogBtn);
        myThread = new MyThread(this);


        startLogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(myThread).start();
            }
        });
   }

   public void setValue(int value){
       this.myValue= value;

   }
   
}

When I Click the startLogButton it goes to a white screen and then restart the app. What should I do? I have no idea what has gone wrong.

Thanks in advance.

1 Answers1

0

The issue was I have violated the rule "Do not access the Android UI toolkit from outside the UI thread".

ref : https://developer.android.com/guide/components/processes-and-threads

As a solution I found that I can use thread communication using message passing. ref : Communication between UI thread and other threads using handler