开发者

Programing Threads and handlers in android?

i have executed the following code

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);
    }

};

}

the above code is to display the current second on to a TextView continually updating it ...

and i got the following error in my logcat

FATAL EXCEPTION: main android.content.res.Resources$NotFoundException: String resource ID #x22 at android.content.res.Resources.getText(Resources.java:201) at android.widget.TextView.setText(TextView.java:2857) at com.kpj4s.Threads_Handler.Activity_Threads_Handler$1.handleMessage(Activity_Threads_Handler.java:56) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:123) at android.app.ActivityThread.main(ActivityThread.java:3647) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method)

can some one help me out pls .. thanks :)


The problem is:

tv.setText(msg.what);

What are you trying to do?

The problem is that msg.what is an integer and setText receives: either a String or an integer that is an android resource (for instance R.string.something). Thus, if you want to show the msg.what content use tv.setText(String.valueOf(msg.what)) instead.


TextView.setText(int) expects the integer parameter to be a resource identifier. You need to convert it to a String, i.e. you want:

tv.setText(Integer.toString(msg.what)); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜