我执行了以下代码
public class Activity_Threads_Handler extends Activity {
private int mSec;
TextView tv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
startHeavyDutyStuff();
}
void startHeavyDutyStuff() {
// Here is the heavy-duty thread
Thread t = new Thread() {
public void run() {
try {
while (true) {
mSec = Calendar.getInstance().get(Calendar.MINUTE);
// Send update to the main thread
messageHandler.sendMessage(Message.obtain(
messageHandler, mSec));
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
// Instantiating the Handler associated with the main thread.
private Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
tv.setText(msg.what);
}
};
}
上面的代码是显示当前第二个到TextView不断更新它...
我的logcat
中出现以下错误致命的例外:主要 android.content.res.Resources $ NotFoundException:字符串资源ID#x22 在android.content.res.Resources.getText(Resources.java:201) 在android.widget.TextView.setText(TextView.java:2857) at com.kpj4s.Threads_Handler.Activity_Threads_Handler $ 1.handleMessage(Activity_Threads_Handler.java:56) 在android.os.Handler.dispatchMessage(Handler.java:99) 在android.os.Looper.loop(Looper.java:123) 在android.app.ActivityThread.main(ActivityThread.java:3647) at java.lang.reflect.Method.invokeNative(Native Method) 在java.lang.reflect.Method.invoke(Method.java:507) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 在dalvik.system.NativeStart.main(本地方法)
有人可以帮我解决.. 谢谢:))
答案 0 :(得分:2)
问题是:
tv.setText(msg.what);
你想做什么?
问题是msg.what
是一个整数,setText
接收:String
或整数是一个android资源(例如R.string.something)。因此,如果您想要显示msg.what
内容,请使用tv.setText(String.valueOf(msg.what))
。
答案 1 :(得分:1)
TextView.setText(int)
期望整数参数是资源标识符。您需要将其转换为String
,即您想要:
tv.setText(Integer.toString(msg.what));