此警报对话框出错

时间:2016-09-22 05:22:36

标签: java android android-alertdialog android-context

这是我的代码,

b3.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {

        if (v == b3) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Delete")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            mydb.deleteContact(id_To_Update);
                            Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            // User cancelled the dialog
                        }
                    });
            AlertDialog d = builder.create();
            d.setTitle("Are you sure");
            d.show();
        }
    }

});

if (!rs.isClosed()) {
    rs.close();
}
name.setText(nam);
email.setText(emai);

当我在删除按钮上使用此代码时,首先出现错误“this”。怎么解决?如何使用删除确认消息?

请帮帮我。提前谢谢!

2 个答案:

答案 0 :(得分:2)

使用上下文而不仅仅是"这个"参考。您可以在此处使用Activity上下文,而不是任何其他上下文。有关详情,请访问这些链接ContextAlertDialog.Builder

对于活动:

 AlertDialog.Builder builder = new AlertDialog.Builder(ActivityName.this);

对于片段:

 AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

由于

答案 1 :(得分:0)

您需要替换

AlertDialog.Builder builder = new AlertDialog.Builder(this);

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivityName.this);