Android启动PopUpClass报View.getContext()空指针异常怎么解决
异常产生原因
- 直接触发崩溃的核心原因:
PopUpClass中声明的成员变量View view从未被初始化赋值,始终为null值,在onCreate方法中调用view.getContext()时触发空指针异常,和堆栈报错的位置完全匹配。 - 额外不合理逻辑:
PopUpClass继承自AppCompatActivity,本身就是合法的Context实例,完全不需要通过View对象获取Context。NewHomeFragment跳转前手动调用PopUpClass popUpClass = new PopUpClass();属于无效操作,Android的Activity实例由系统负责创建和生命周期管理,手动new的实例不会参与任何生命周期回调,也没有实际作用。- Activity承载弹窗场景下额外嵌套
PopupWindow属于冗余设计,可直接简化。
可行修复方案
方案一:保留原有PopupWindow逻辑,修复空指针
只需修改PopUpClass中错误的代码部分即可:
- 删除未初始化的成员变量
View view; - 修改LayoutInflater获取逻辑,用Activity本身作为Context获取:
// 替换原来的view.getContext()获取逻辑,可直接用Activity自带的getLayoutInflater方法 LayoutInflater inflater = getLayoutInflater(); View popupView = inflater.inflate(R.layout.activity_agreement_consent_popup, null);
- 修改PopupWindow的展示锚点,用Activity的根布局代替null的view:
popupWindow.showAtLocation(findViewById(android.R.id.content), Gravity.FILL, 0, 0);
- 删掉
NewHomeFragment中无用的PopUpClass popUpClass = new PopUpClass();代码行。
方案二:简化冗余逻辑,移除不必要的PopupWindow
如果不需要PopupWindow的特殊交互逻辑,可直接把弹窗布局设为Activity的内容视图,代码更简洁易维护:
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 直接设置弹窗布局为Activity的内容视图 setContentView(R.layout.activity_agreement_consent_popup); agreementContent = getIntent().getStringExtra("AgreementContent"); ScrollView sView = findViewById(R.id.sView); WebView agreementText = findViewById(R.id.agreement_textView); Button buttonEdit = findViewById(R.id.btn); sView.setVerticalScrollBarEnabled(true); sView.setHorizontalScrollBarEnabled(false); agreementText.loadDataWithBaseURL(null, agreementContent, "text/html", "UTF-8", null); buttonEdit.setOnClickListener(v -> { WirelessAPI_Task task = new WirelessAPI_Task(this); task.callback = this; task.execute(WirelessAPI_Task.INSERT_USER_CONSENT); }); }
如需实现和PopupWindow一致的浮层效果,可在AndroidManifest.xml中给PopUpClass配置弹窗主题:
<activity android:name=".view.PopUpClass" android:theme="@style/Theme.MaterialComponents.DayNight.Dialog" />
同样需要删除NewHomeFragment中无用的手动创建PopUpClass实例的代码。
内容的提问来源于stack exchange,提问作者bablu
相关产品推荐
相关产品推荐

