Handler postDelayed - print every second something
Working answer:
int t = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
t++;
textView.setText(getString(R.string.formatted_time, t));
if(t<10) {
handler.postDelayed(this, 1000);
}
}
}, 1000);
Where formatted_time is something like that:
<string android:name="formatted_time">%d seconds</string>
I am using handler for delay in android but it's not working
You are using postDelayed
incorrectly. It looks like you expect it to work the same way Thread.sleep
would work. However that is not the case.
Here is a correct implementation of what you are trying to achieve:
private Handler handler = new Handler();
private TextView textView;
private int i = 0;
private boolean flip;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.hello);
handler.post(hello_first);
}
private Runnable hello_first = new Runnable() {
@Override
public void run() {
if(++i == 5) {
handler.removeCallbacks(this);
return;
}
if(flip) {
textView.setText("Nice Work");
} else {
textView.setText("Hello");
}
flip = !flip;
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(2));
}
};
Android postDelayed does not delay
When you call postDelayed()
, it just places the Runnable
in a queue and returns immediately. It does not wait for the runnable to be executed.
If you need something to happen after a delay, put the code in the run()
method of the runnable.
How to call a method after a delay in Android
Kotlin
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)
Java
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
Related Topics
Converting Exponential Value in Java to a Number Format
The Import Org.Junit Cannot Be Resolved
Eclipse No Tests Found Using Junit 5 Caused by Noclassdeffounderror for Launcherfactory
Java.Lang.Noclassdeffounderror: Com/Fasterxml/Jackson/Databind/Exc/Invaliddefinitionexception
Split Comma Separated Values in Java, Int and String
Spring Security Configuration Filter Any Requests Except a Specific Endpoint
How to Handle Errors in Spring-Webflux
Get the Nearest Date to Specific from the List of Dates
How to Find Max Duplicate Number Count in Given Array Using for Loop
In Java, How to Combine Two Json Arrays of Objects
Javax.Net.Ssl.Sslexception: Certificate Doesn't Match Any of the Subject Alternative Names
Changing Scene When a Button Is Pressed Fxml
Default Value in Lombok. How to Init Default With Both Constructor and Builder
Kafka Consumer in Java Not Consuming Messages
How to Parallelize a Foreach Loop in Java
Limiting the Number of Characters in a String, and Chopping Off the Rest