Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

Thread in Android ---> Unfortunately ThreadApp has Stopped

I have one textview, which i can use to show countdown timer. I wanted to use Thread class which takes Runnable interface.

I wrote the following code for the same but it is gives run time error Unfortunately ThreadApp has Stopped

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity implements Runnable
{

TextView tvTimer;
Thread timerThread;
int time=30;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvTimer =(TextView)findViewById(R.id.textView1);
    timerThread= new Thread(this);
    timerThread.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public void run()
{
    try
    {
        Thread.sleep(1000);
        tvTimer.setText((String.valueOf(time)).toString());
        time--;
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

}

At the same time when i removed tvTimer.setText((String.valueOf(time)).toString()); it works fine. Can anyone provide me the solution. I am new in android.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use updating UI using RunOnUiThread like this

 @Override
    public void run()
    {
    try
    {
        Thread.sleep(1000);
       runOnUiThread(new Runnable() {
      public void run() {
              tvTimer.setText((String.valueOf(time)).toString());                       
        }
        });
        time--;
      }
      catch (InterruptedException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }

     }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...