Thursday, 12 September 2013

Resource not found exception when setting number into EditText

If you try to set a number (integer) to editText with the follow code, it will crash:

editText.setText(0);

Error trace:
E/AndroidRuntime(23189): FATAL EXCEPTION: main
E/AndroidRuntime(23189): android.content.res.Resources$NotFoundException: String resource ID #0x1
E/AndroidRuntime(23189): at android.content.res.Resources.getText(Resources.java:230)
E/AndroidRuntime(23189): at android.widget.TextView.setText(TextView.java:3769)
E/AndroidRuntime(23189): at com.jiahaoliuliu.android.numberstepper.MainActivity$1.onClick(MainActivity.java:31)
E/AndroidRuntime(23189): at android.view.View.performClick(View.java:4204)
E/AndroidRuntime(23189): at android.view.View$PerformClick.run(View.java:17355)
E/AndroidRuntime(23189): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(23189): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(23189): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(23189): at android.app.ActivityThread.main(ActivityThread.java:5041)
E/AndroidRuntime(23189): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(23189): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(23189): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(23189): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(23189): at dalvik.system.NativeStart.main(Native Method)

This is because the class EditText has the method called setText which expects to receive a resource id, which matches with some resources stored in R.java class generated.

EditText.setText(int resId);

To solve it, the app must convert the number(integer) into a String.

editText.setText(String.valueOf(0));

For more info:

No comments:

Post a Comment