findviewbyid returns null in a dialog

In my case: First I must call the

dialog.show(),

and only after it I was able to use

dialog.findviewById(R.id.myID).

If I missed to call the show(), than I got a null back with findViewByID.


Try this:

EditText et = (EditText)textEntryView.findViewById(R.id.username_edit);

You have to tell in which view to find the id. Otherwise it will try to find the id in the view from the xml layout inflated by setContentView (usually declared in onCreate)


I faced a similar problem. In my case, I had a dialog with custom layout and in this layout had a radioButton. In order to solve that, I used the follow code:

View dialogLayout = factory.inflate(R.layout.dialog_layout, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setView(dialogLayout);

RadioButton radiobt = (RadioButton) dialogLayout.findViewById(R.id.radioBt);

I was having the same problem, which presented itself in the following code snippet:

final Dialog dialog = new Dialog(this);

dialog.setContentView(R.layout.addbank_dialog);
dialog.show();

Button btnSaveBank = (Button)dialog.findViewById(R.id.btnSaveBank);

final EditText etBankName = (EditText)dialog.findViewById(R.id.etBankName);

btnSaveBank.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        try{
            String bank = etBankName.getText().toString();
            SharedCommonData.dbOps.saveBankInDB(bank);
        }
        catch(Exception e){
            e.printStackTrace();
        }
        Toast.makeText(SharedCommonData.context, "Bank Saved", Toast.LENGTH_SHORT);
        refreshBanks();
        dialog.dismiss();
    }
});

etBankName was returning null value, but then I used dialog.findviewbyid(R.id.etBankName) and it worked.