Im trying to create a simple high/low app but the application crashes when I try to get a random number.
Here is some code:
final TextView counter = (TextView) findViewById(R.id.tcounter);
Button high = (Button) findViewById(R.id.bhigh);
Button low = (Button) findViewById(R.id.blow);
Button start = (Button) findViewById(R.id.bplay);
final Random rstart = new Random();
final int counternr = rstart.nextInt(5) + 1;
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
counter.setText(counternr);
That is supposed to set the TextView “counter” to a random number from 1-6, but gives me a crash.
Thanks in advance!
EDIT: Here is the error text:
11-23 20:17:40.509: ERROR/AndroidRuntime(765): FATAL EXCEPTION: main
11-23 20:17:40.509: ERROR/AndroidRuntime(765): java.lang.RuntimeException: Unable to start activity ComponentInfo{xxx.xxx.xxx/xxx.xxx.xxx.play}: java.lang.NullPointerException
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.os.Handler.dispatchMessage(Handler.java:99)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.os.Looper.loop(Looper.java:123)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at java.lang.reflect.Method.invokeNative(Native Method)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at java.lang.reflect.Method.invoke(Method.java:507)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at dalvik.system.NativeStart.main(Native Method)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): Caused by: java.lang.NullPointerException
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at xxx.xxx.xxx.play.onCreate(play.java:26)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-23 20:17:40.509: ERROR/AndroidRuntime(765): ... 11 more
Very messy, but I hope it is OK.
Change this
with this
The method
setTextaccepts only aCharSequenceobject as argument (in this case, aString), or anintif it represents a resource ID