Android Studio模拟器点击登录按钮崩溃问题求助
问题解决:登录跳转库存界面崩溃
错误原因
从LogCat错误信息可直接定位问题:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
错误指向InventoryScreen.java:18,核心问题是:你在InventoryScreen的onCreate方法中,直接给buttonSMS设置点击监听,但未通过findViewById初始化该按钮实例,导致空指针异常,最终引发应用崩溃。
修复代码
修改InventoryScreen代码,在设置监听前先完成按钮初始化(若后续要使用buttonSignOut,也需同步初始化):
package com.example.cs360projectone; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class InventoryScreen extends AppCompatActivity { Button buttonSMS, buttonSignOut; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inventory_screen); // 新增:初始化buttonSMS,需与布局文件中的id完全匹配 buttonSMS = findViewById(R.id.buttonSMS); // 若后续要使用buttonSignOut,同样需要初始化 // buttonSignOut = findViewById(R.id.buttonSignOut); buttonSMS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view1) { openSMSPermission(); } }); } public void openSMSPermission() { Intent intent = new Intent(this, SMSPermissionScreen.class); startActivity(intent); } }
额外注意事项
- 确认布局文件
activity_inventory_screen.xml中,对应按钮的android:id确实为@+id/buttonSMS,id不匹配会导致findViewById返回null; - 所有需要操作的View控件,必须先调用
findViewById完成初始化,再执行设置监听、修改属性等操作; - 可养成固定流程:在
setContentView之后,先完成所有控件初始化,再编写业务逻辑,避免遗漏初始化步骤。
内容的提问来源于stack exchange,提问作者Britteny
相关产品推荐
相关产品推荐

