Search code examples
javaandroidandroid-fragmentsandroid-alertdialog

Alert dialog in Fragment, app get crashed


I want to display the alert dialog when onClick of the button in fragment layout. I have tried but the app is crashing when it runs.

 @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    binding = FragmentWalletBinding.inflate(inflater, container, false);

    Button button = (Button)getView().findViewById(R.id.add_money);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            AlertDialog.Builder alertdialog = new AlertDialog.Builder(view.getContext());
            alertdialog.setMessage("this is message");
            alertdialog.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Toast.makeText(getContext(),"toast message",Toast.LENGTH_SHORT).show();
                }
            }).show();
        }
    });

    return binding.getRoot();
}

log message


Solution

  • onCreateView returns View which can be further obtained by getView() method. and you are calling it before onCreateView had a chance to return own View for framework (its still inside method, didn't return binding.getRoot(); yet)

    if you are using view binding then obtain your Button from there

    Button button = (Button) binding.addMoney;
    

    or even just use strictly (without additional local Button)

    binding.addMoney.setOnClickListener(...
    

    and if you REALLY WANT to use findViewById (but why...), then you can look inside binding.getRoot() even when it isn't returned/drawn yet

    Button button = (Button) binding.getRoot().findViewById(R.id.add_money);