You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android程序运行报错:findViewById触发NullPointerException求助

Android程序启动崩溃:findViewById引发空指针异常

程序启动后直接终止,错误源自MainActivity第19行的findViewById调用,触发空指针异常。

Logcat错误日志

---------------------------- PROCESS STARTED (10563) for package com.example.test0 ----------------------------
2023-05-23 15:20:13.344 10563-10563 AndroidRuntime          com.example.test0                    E  FATAL EXCEPTION: main
Process: com.example.test0, PID: 10563
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.test0/com.example.test0.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2835)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2913)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1615)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6687)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.Button.findViewById(int)' on a null object reference
at com.example.test0.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:7028)
at android.app.Activity.performCreate(Activity.java:7019)

MainActivity代码

public class MainActivity extends AppCompatActivity {
Button button;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button.findViewById(R.id.button);  //<<<<<<==== line19
    editText.findViewById(R.id.editText);
}
}

相关说明

  • 布局截图显示界面包含Button和EditText控件,对应id分别为button和editText
  • 已尝试更换多种模拟器及真机测试,问题仍存在

解决方案

错误原因是button和editText变量未初始化(默认值为null),直接调用它们的findViewById方法必然触发空指针异常。正确做法是调用Activity的findViewById方法获取控件实例,并赋值给对应变量:

修改onCreate方法中的代码:

button = findViewById(R.id.button);
editText = findViewById(R.id.editText);

这样就能正确获取到布局中的控件,避免空指针异常。

内容的提问来源于stack exchange,提问作者M.R.E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:37:14