从Alertdialog启动自定义对话框 - 空指针错误

时间:2012-02-02 16:54:03

标签: android alertdialog

我正在尝试从警报对话框中按下按钮启动自定义对话框。用户按下主UI中的按钮以打开redeemAlertDialog,该对话框询问用户他们是否确定要继续此操作。如果他们单击“是”,那么我想打开我的自定义对话框。但是,启动我的自定义对话框会导致应用程序崩溃。 Logcat告诉我,我在行* text.setText(“Blah Blah”/ merchantName /); *上有一个空指针错误,但如果我注释掉这一行,我会得到同样的错误line button.setOnClickListener(new OnClickListener(){ 如果我注释掉这两行,那就行了。在挖掘之后,我认为我的问题与我关联自定义对话框的上下文有关,当我创建它但我无法解决它。如果有人能指出我出错的地方,我会很感激。 我的代码如下。

解决 在我的onCreate方法中,我从mContext = getApplicationContext()更改了mContext的定义;到mContext = this; 由于某些原因couponDialog = new Dialog(mContext);不喜欢getApplicationContect();

给出的内容
    private void redeem() {
    AlertDialog.Builder redeemAlerDialogBuilder = new AlertDialog.Builder(this);
    redeemAlerDialogBuilder.setMessage("Are you sure you want to redeem?")
           .setCancelable(false) //User must select a button, can't use the back button
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   //Do something to launch a redeem dialog
                   //openCouponDialog();
                   couponDialog = new Dialog(mContext);
                   couponDialog.setContentView(R.layout.redeem_layout);
                   couponDialog.setTitle("Freebie Coupon");
                   couponDialog.setCancelable(false); //User should only be able to exit dialog by clicking done

                   TextView text = (TextView) findViewById(R.id.redeemMerchantName);
                   text.setText("Blah Blah"/*merchantName*/);

                   ImageView image = (ImageView) findViewById(R.id.couponImage);
                   //Set merchant coupon image here - need to download this from server when merchant is first added

                   Button button = (Button) findViewById(R.id.redeemDialogCloseButton);
                   button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();           
                        }           
                   });

                   couponDialog.show();
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {             
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel(); //Cancel redeem                
            }
        });
    redeemAlertDialog = redeemAlerDialogBuilder.create();
    redeemAlertDialog.show();
}

1 个答案:

答案 0 :(得分:3)

而不是:

Button button = (Button) findViewById(R.id.redeemDialogCloseButton);

TextView text = (TextView) findViewById(R.id.redeemMerchantName);

使用

Button button = (Button) couponDialog.findViewById(R.id.redeemDialogCloseButton);
TextView text = (TextView) couponDialog.findViewById(R.id.redeemMerchantName);

希望这有效