Search code examples
javaandroidxmltextview

How to Autoincrement the TextView value in Android Studio


I want to Increment the TextView's value in Android Studio automatically but the problem i am facing is > when i run the following code it only show the app interface when the code is finished. Any Solution?

package com.example.assignment2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import static android.os.SystemClock.sleep;

public class MainActivity extends AppCompatActivity{
private TextView tv;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = findViewById(R.id.t);
    while(count<10000000) {
    count++;
    tv.setText("" + count);
    }
}

}


Solution

  •    new Thread(new Runnable(){
            @Override
            public void run() {
                int counter = 0;
                while (counter < 10000000) {
                    counter++;
                    final String counterStr = counter.toString();
                    tv.post(new Runnable(){
                        @Override
                        public void run() {
                            tv.setText(counterStr);
                        }
                    });
                    Thread.sleep(1000);
                    }
                }
            }).start();