djmloody27 djmloody27 - 6 months ago 18
Android Question

Counter in loop

How to do sample counter in Activity? This is not working.

public class MainActivity extends AppCompatActivity implements Runnable {

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

run();
}

@Override
public void run() {
while (true) {
updateTv();

try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void updateTv() {
int counter = 100;
final TextView tv = (TextView) findViewById(R.id.tv);
tv.setText(String.valueOf(counter));
counter--;
}
}

Answer

In onCreate() you're starting an infinite loop inside of the UI thread, blocking it completely. Alternatively you could use a Handler for periodic updates. Maybe using a bigger delay and stop it sometime.

public class MainActivity extends AppCompatActivity implements Runnable {
    private final Handler mHandler = new Handler();

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

        run();
    }

    @Override
    public void run() {
        updateTv();
        mHandler.postDelayed(this, 17);
    }

    public void updateTv() {
        int counter = 100;
        final TextView tv = (TextView) findViewById(R.id.tv);
        tv.setText(String.valueOf(counter));
        counter--;
    }
}

Anyway you should read What is the Android UiThread (UI thread) for sure.

Comments