I’m trying to make a simple counter that counts from 5 to 1 and updates the view after every second. I’ve tried doing it without the handler and just with a simple loop, but it just shows me 1 after waiting or it force closed. I have tried messing with runOnUIThread and threads too, but I’m missing something.
Here’s my code:
package com.ammad.test;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
public class Main extends Activity {
TextView tv;
Button b1;
Handler mHandler;
int i = 5;
private Runnable runnable;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvShow);
b1 = (Button) findViewById(R.id.bt1);
runnable = new Runnable() {
public void run() {
// do your stuff - don't create a new runnable here!
tv.setText(String.valueOf(i));
i--;
mHandler.postDelayed(runnable, 500);
}
};
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
mHandler.post(runnable);
mHandler.removeCallbacks(runnable);
}
});
}
public void doTheLoop() {
/*
* runOnUiThread(new Runnable() {
*
* public void run() { for (int i = 5; i >= 1; i--) { // TODO
* Auto-generated method stub tv.setText(Integer.toString(i)); for (int
* j = 0; j < 200000; j++) ; } }
* `enter code here`
* });
*/
// mHandler.post(runnable);
}
}
Where are you instantiating
mHandler? I think that code is missing, or else this would fail with a NullPointerException. It’s important because if you just instantiate it with the no-arg constructor inonCreateit will use the message queue of the UI thread.There are other issues with this though: inside your
Runnable.runmethod you don’t actually check ifiis less than zero, so it will always callpostDelayedwith itself. Furthermore, you’re updating the UI (setText) from a non-UI thread, which may cause undefined behavior.I think your code is just a bit more complicated than it needs to be. If this example is dumbed down to and hides your actual intent, this is an example might be too simple, but here’s something that basically works, although you’ll need to edit it a bit to compile (catch InterruptedException, etc)