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

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

Read more 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();
}

Answer

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);

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles