我正在尝试创建一个简单的线程,在一段时间后更改文本视图
问题是,当我第二次单击按钮时,我的应用程序崩溃了,我不明白为什么。当我第二次点击按钮时,应该会再次发生同样的情况。
任何帮助表示赞赏。
public class main extends Activity {
Boolean grabar = false;
TextView texto;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
texto = (TextView) findViewById(R.id.texto);
Button startbtn = (Button) findViewById(R.id.button);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
background.start();
}
});
}
Thread background = new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto.setText("ok");
}
};
}
The problem is that when i click the button for the second my application crashes and i don't understand why. When i clink the button for the second time is suppose to the same all over again.
Any help is appreciated.
public class main extends Activity {
Boolean grabar = false;
TextView texto;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
texto = (TextView) findViewById(R.id.texto);
Button startbtn = (Button) findViewById(R.id.button);
startbtn.setOnClickListener(new OnClickListener(){
public void onClick(View v){
background.start();
}
});
}
Thread background = new Thread (new Runnable() {
public void run() {
try {
Thread.sleep(3000);
cambiarHandler.sendEmptyMessage(0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Handler cambiarHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
texto.setText("ok");
}
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我看到的问题是线程被设计为运行一次。每次您希望运行该线程时,都需要创建该线程的一个新实例。
The problem I see is that threads are designed to run once. You need to create a new instance of the thread each time you wish to run it.
这很可能和Android只允许UI线程修改UI的政策有关。
如果您想从单独的线程修改 UI,则应该使用 ASyncTask。
请参阅此处:
从线程更新 UI
This may well have something to do with Android's policy of only allowing the UI thread to modify the UI.
You should be using ASyncTask instead if you want to modify the UI from a separate thread.
See here:
Update UI from Thread
我不知道抛出了哪个异常。我猜这是 NPE 抛出的。当您尝试将文本设置为
TextView
时。尝试在handleMessage()
方法中实例化TextView
:并在 onClick 方法中执行此操作,以便每次单击按钮时都有新的线程实例。
I don't know which exception is thrown. I guess it is NPE thrown. When you try to set text to the
TextView
. Try instantiating theTextView
within thehandleMessage()
method:And in the onClick method do this to have new instance of the thread each time button is clicked.