Android Studio按钮关联空指针异常崩溃问题求助
问题描述
定义Button变量后应用持续崩溃,错误提示空对象引用,但Ctrl点击按钮ID能正常定位到布局中的按钮。
原MainActivity.java代码
package com.example.datasaving; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { Button button = this.findViewById(R.id.SAVE); TextView InputID = findViewById(R.id.textView); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = InputID.getText().toString(); Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show(); } }); } }
activity_main.xml代码
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/SAVE" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/save" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:hint="@string/enter_your_gmail" android:textColorHint="#757575" app:layout_constraintBottom_toTopOf="@+id/SAVE" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
运行错误日志
FATAL EXCEPTION: main Process: com.example.datasaving, PID: 6961 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datasaving/com.example.datasaving.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3921) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4078) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:103) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2423) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:233) at android.os.Looper.loop(Looper.java:334) at android.app.ActivityThread.main(ActivityThread.java:8348) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1065) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at com.example.datasaving.MainActivity.onCreate(MainActivity.java:20) at android.app.Activity.performCreate(Activity.java:8363) at android.app.Activity.performCreate(Activity.java:8341) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1329) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3894) ... 12 more
问题原因与修复
这是代码执行顺序错误导致的空指针异常,和Android Studio无关。
在Android开发中,findViewById()必须在setContentView()之后调用——setContentView()是将布局文件加载到Activity的核心步骤,只有布局加载完成后,系统才能通过控件ID找到对应的视图实例。原代码中先调用findViewById()获取控件,之后才执行super.onCreate(savedInstanceState)和setContentView(),此时布局未加载,findViewById()返回null,后续调用button.setOnClickListener()就会触发空指针异常。
修正后的MainActivity.java代码
package com.example.datasaving; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { // 先执行父类初始化与布局加载 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 布局加载完成后再获取控件实例 Button button = this.findViewById(R.id.SAVE); TextView InputID = findViewById(R.id.textView); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String msg = InputID.getText().toString(); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } }); } }
注:顺便将原代码中空内容的Toast改为显示输入文本,让功能更完整。
内容的提问来源于stack exchange,提问作者Divyansh undley
相关产品推荐
相关产品推荐

