javaandroid

My application crashes when I try to call OnClickListener in a dialog box


This Error

 private void showDialog(){
        Dialog dialogAI = new Dialog(this, R.style.DialogStyle);

        dialogAI.setContentView(R.layout.custom_dialog_ai);
        dialogAI.getWindow().setBackgroundDrawableResource(R.drawable.bg_cyrcle_window);

        TypeWriterView typeWriterView = findViewById(R.id.typeWriter_openai);
        AppCompatButton appCompatButton = findViewById(R.id.btn_yes);
        

        #### THIS CRASHING MY APP ####
        appCompatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                typeWriterView.animateText("Привет, чем я могу помочь?");
            }
        });

        dialogAI.show();
    }

Solution

  • You are missing the crash log. Please post it. However, most likely cause of the crash is that you're calling findViewById on the Activity's view hierarchy, but the views (typeWriter_openai and btn_yes) are actually part of the Dialog's layout, not the Activity's.

    You need to call findViewById on the dialog, not on this (the activity):

    TypeWriterView typeWriterView = dialogAI.findViewById(R.id.typeWriter_openai);
    AppCompatButton appCompatButton = dialogAI.findViewById(R.id.btn_yes);