Search code examples
androidtextviewsettextthread-sleep

Android App stops after TextView text is changed


I have made an android app, which has two TextViews. When I change the text using setText() then the app stops. I have read other answers on StackOverflow and have implemented them in my program, but the problem still persists.

Here is my onCreate() code:

TextView ec, vc;
Thread t;

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

    ec = (TextView) findViewById(R.id.ce);
    vc = (TextView) findViewById(R.id.cv);
    t = new Thread(new Runnable() {@Override public void run() {loop();}});
    t.start();
}

Here is my loop() code:

public void loop()
{
    try{Thread.sleep(7000);}catch(Exception e){}
    ec.setText("");
    vc.setText("");
    try{Thread.sleep(53000);}catch(Exception e){}
    t.stop();
}

I want to empty the text of both the TextViews after 7 seconds. But when I run my app, after 7 seconds, it stops.

Other answers on StackOverflow say that I should put setContentView(R.layout.activity_main); before I initiate the ec and vc variables. It is already there, but still the app stops.

Please help me.


Solution

  • You can use the View.postDelayed method to run a Runnable on the UIThread after a certain time.