横竖屏切换时,禁止activity重新创建,导致getActivity为null

本文解决在创建AlertDialog时遇到的NullPointerException问题。原因在于getActivity返回null。解决方案是在<activity>标签中设置android:configChanges属性,并对getActivity进行判空处理。

遇到的问题如下:

出现问题代码如下:

private AlertDialog.Builder glxssConnectionDialog(){
    if(getActivity()==null){
        return null;
    }
    final AlertDialog.Builder normalDialog = new AlertDialog.Builder(getActivity());
    normalDialog.setTitle(R.string.dialog_connection_title);
    normalDialog.setMessage(R.string.dialog_connection_message);
    normalDialog.setNeutralButton(R.string.dialog_connection_positiveButton,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    CameraFragment.this.getActivity().finish();
                }
            });
    normalDialog.setCancelable(false);
    normalDialog.create();
    return normalDialog;
}

代码问题如下:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:225)
at android.app.AlertDialog$Builder.<init>(AlertDialog.java:459)
at com.llvision.app.CameraFragment.f(CameraFragment.java:1250)
at com.llvision.app.CameraFragment.x(CameraFragment.java:66)
at com.llvision.app.CameraFragment$10.handleMessage(CameraFragment.java:281)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6595)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)

at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)

创建dialog时,获取到的getActivity为null,造成出现上述问题。

解决办法:

需要在manifest中<activity>标签中加入android:configChanges="keyboardHidden|orientation|screenSize"属性。

此属性的作用是横竖屏切换时,禁止activity重新创建,防止getActivity为null。创建dialog时,对getActivity做判null处理。

加入android:configChanges="keyboardHidden|orientation"属性,在低版本上,这个是可以起作用。在android 4.0 以上实际上这个是不起作用的。

必须要加上screenSize。

android:configChanges="keyboardHidden|orientation|screenSize"

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

闲暇部落

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值