Answer the question
In order to leave comments, you need to log in
Java why hangs while loop in background thread?
Good afternoon, I just started learning Java + android studio and immediately ran into a problem: I am writing a simple application - I want the button to start / stop the counter (1,2,3,4 ......)
I can’t understand why the application freezes and stops answer if in the background thread I do the counter in the while loop.
here is the code:
public class MainActivity extends AppCompatActivity {
private Button my_button;
private boolean start_stop = false;
private int counter = 0;
private TextView my_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_button = findViewById(R.id.My_Button);
my_text = findViewById(R.id.my_text);
}
public void onClick_button(View view) {
if(start_stop != true) {
my_button.setText("STOP");
start_stop = true;
runOnUiThread(new Runnable() {
@Override
public void run() {
while (start_stop) {
my_text.setText(Integer.toString(counter));
counter++;
try {
Thread.sleep(1000); // sleep 1 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
}else {
my_button.setText("START");
start_stop = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
start_stop = false;
}
Answer the question
In order to leave comments, you need to log in
as usual, the solution was found on Stackoverflow
package com.example.switch_pictures;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button my_button;
private boolean start_stop = false;
private int counter = 0;
private TextView my_text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
my_button = findViewById(R.id.My_Button);
my_text = findViewById(R.id.my_text);
}
public void onClick_button(View view) {
if(start_stop != true) {
my_button.setText("STOP");
start_stop = true;
new Thread(new Runnable() {
@Override
public void run() {
while (start_stop) {
runOnUiThread(new Runnable() {
@Override
public void run() {
my_text.setText(Integer.toString(counter));
}
});
counter++;
try {
Thread.sleep(100); // sleep 1 sec
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}else {
my_button.setText("START");
start_stop = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
start_stop = false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question