我在尝试实现onClickListener时总是收到错误。
有我的代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_submit = (Button) findViewById(R.id.btn_submit);
btn_submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
这是我的XML代码: logcat的
06-07 02:54:05.901: E/AndroidRuntime(19667): FATAL EXCEPTION: main
06-07 02:54:05.901: E/AndroidRuntime(19667): Process: com.gonzalo.ejemplo, PID: 19667
06-07 02:54:05.901: E/AndroidRuntime(19667): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gonzalo.ejemplo/com.gonzalo.ejemplo.MainActivity}: java.lang.NullPointerException
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread.access$900(ActivityThread.java:161)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.os.Handler.dispatchMessage(Handler.java:102)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.os.Looper.loop(Looper.java:157)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread.main(ActivityThread.java:5356)
06-07 02:54:05.901: E/AndroidRuntime(19667): at java.lang.reflect.Method.invokeNative(Native Method)
06-07 02:54:05.901: E/AndroidRuntime(19667): at java.lang.reflect.Method.invoke(Method.java:515)
06-07 02:54:05.901: E/AndroidRuntime(19667): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
06-07 02:54:05.901: E/AndroidRuntime(19667): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
06-07 02:54:05.901: E/AndroidRuntime(19667): at dalvik.system.NativeStart.main(Native Method)
06-07 02:54:05.901: E/AndroidRuntime(19667): Caused by: java.lang.NullPointerException
06-07 02:54:05.901: E/AndroidRuntime(19667): at com.gonzalo.ejemplo.MainActivity.onCreate(MainActivity.java:27)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.Activity.performCreate(Activity.java:5426)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
06-07 02:54:05.901: E/AndroidRuntime(19667): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
06-07 02:54:05.901: E/AndroidRuntime(19667): ... 11 more
06-07 02:59:05.974: I/Process(19667): Sending signal. PID: 19667 SIG: 9
所以..任何想法我该如何解决?
由于
答案 0 :(得分:1)
findViewById
可能返回null。确保布局中有一个带有android:id="@+id/btn_submit"
的按钮。
答案 1 :(得分:1)
这个变量可能是问题。
Button btn_submit = (Button) findViewById(R.id.btn_submit);
签入activity_main.xml
如果存在btn_submit
,可能还有其他名称。