设置对话框背景可绘制时,Android NullPointerException

时间:2019-03-02 20:47:09

标签: java android

设置“对话框”背景可绘制时,我得到警告方法调用“ setBackgroundDrawable”可能会产生“ java.lang.NullPointerException” 。我将如何防止此类异常?

class UIManager {

    private Context context;
    private MapActivity activity;
    private Dialog dialog;

    UIManager(MapActivity activity, Context context) {
        this.activity = activity;
        this.context = context;
        this.dialog = new Dialog(context);

        dialog.setContentView(R.layout.upload_dialog);

        /* THIS LINE */
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        dialog.setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);
    }

    void showUploadDialog() {
        dialog.show();
    }

    void dismissUploadDialog() {
        dialog.dismiss();
    }
    ...
}

1 个答案:

答案 0 :(得分:0)

您可以通过检查dialog.getWindow()是否返回null来防止该异常。但是实际上,这种情况永远不会发生,因为只有在未显示绑定到的活动时,它才会返回null。