it might be my limited experience, but I just ran into a weird error which confuses me. I have an Activity with a bunch of buttons which are then assigned into a 2-Dimensional Array (btns[][]). Initially, I used to set an OnClick Listener by using an anonymous class, which would basically be the following, for each and every button:
btns[x][y].setOnClickListener(new OnClickListener(() {
onClick(View v) {
btns_OnClick(x, y, btns[x][y]);
}
Not that x and y in this case were hard coded constants.
Since this was really bugging me, I implemented:
private class TimerButtonOnClickListener implements OnClickListener {
int[] crds;
public TimerButtonOnClickListener(int row, int col) {
crds = new int[] { row, col };
}
public void onClick(View v) {
btns_OnClick(crds[0], crds[1],
btns[crds[0]][crds[1]]);
}
}
And assign the Listener to the Buttons as follows:
for (int i = 0; i < 6; i++)
for (int j = 0; j < 2; j++)
btns[i][j].setOnClickListener(new TimerButtonOnClickListener(i, j));
The above happens in onCreate, yet the crash does not occur immediately. Actually, I have no Idea where it crashes. LogCat gives
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.LoadedApk$ServiceDispatcher.doConnected(LoadedApk.java:1061)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1078)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
I use a handler to invoke a ui update from a Timer Task, but even if I remove the timer I still receive this error, so its probably not my own Handler breaking there.
I did not make any changes to the source apart from that. (I even diff’d, and I also didn’t touch any other file.)
What did I do wrong?
The error is not related to buttons. The stacktrace would mention “button”, “onClick” or something button related if that was the case.
Instead the
NullPointerExceptionhappens while the system connects to aService. Looking at the source for the place where the exception happensone can see that it is most likely related to Context#bindService() with a
nullServiceConnection