我遇到问题导致我的应用程序在触摸按钮时崩溃,读取LogCat我发现错误来自TouchEvent。我没有发现问题!这是我的代码:
final Button Dec = (Button)findViewById(R.id.Dec);
Dec.setOnTouchListener(new OnTouchListener () {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
SendCmd(Server.getText().toString(), "keydec.down");
} else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
SendCmd(Server.getText().toString(), "keydec.up");
}
return true;
}
});
以下是LogCat中的内容:
09-05 16:47:05.626: E/AndroidRuntime(11880): FATAL EXCEPTION: main
09-05 16:47:05.626: E/AndroidRuntime(11880): java.lang.NullPointerException
09-05 16:47:05.626: E/AndroidRuntime(11880): at net.shape.remote.RacingPad$1.onTouch(RacingPad.java:46)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.view.View.dispatchTouchEvent(View.java:3762)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
09-05 16:47:05.626: E/AndroidRuntime(11880): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1731)
09-05 16:47:05.626: E/AndroidRuntime(11880): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1120)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.app.Activity.dispatchTouchEvent(Activity.java:2086)
09-05 16:47:05.626: E/AndroidRuntime(11880): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1715)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.view.ViewRoot.handleMessage(ViewRoot.java:1787)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.os.Handler.dispatchMessage(Handler.java:99)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.os.Looper.loop(Looper.java:123)
09-05 16:47:05.626: E/AndroidRuntime(11880): at android.app.ActivityThread.main(ActivityThread.java:4633)
09-05 16:47:05.626: E/AndroidRuntime(11880): at java.lang.reflect.Method.invokeNative(Native Method)
09-05 16:47:05.626: E/AndroidRuntime(11880): at java.lang.reflect.Method.invoke(Method.java:521)
09-05 16:47:05.626: E/AndroidRuntime(11880): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
09-05 16:47:05.626: E/AndroidRuntime(11880): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-05 16:47:05.626: E/AndroidRuntime(11880): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:1)
Server
为空或Server.getText()
返回null。如果你想要有点容错,你应该使用String.valueOf(Server.getText())
:它仍然会给你null,但它不会崩溃。