Othmane Othmane - 1 month ago 8
Android Question

can't get a pointer on my button in a dialogfragment

I am trying to build a simple DialogFragment which contains a textview and two buttons (send and cancel).

I want to disable the button when the textview is first empty, but the positiveButton variable in my code is always null and I get the following exception:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference


This is the code:

public class SendFriendRequestFragment extends DialogFragment {
private TextView tvEmail = null;
Button positiveButton = null;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();

final View layout = inflater.inflate(R.layout.fragment_send_friend_request, null);

// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(layout)
.setTitle("Send request")
.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String email = tvEmail.getText().toString().trim();

if (validateInput()) {
SendFriendRequest(getActivity(), email);
} else {
Toast.makeText(getActivity(), "Request cannot be sent", Toast.LENGTH_LONG).show();
return;
}

}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});

Dialog dialog = builder.create();
positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);

positiveButton.setEnabled(false); // positiveButton is null and this call raises an exception !
tvEmail = (TextView) layout.findViewById(R.id.email);
tvEmail.addTextChangedListener(new InputTextWatcher(tvEmail));
// Create the AlertDialog object and return it
//return builder.create();
return dialog;
}
// Other functions that use the two variables positiveButton and tvEmail ...
}


Could anyone please tell me how to fix my problem and what's the best way to get a pointer of the buttons and the views contained in the used layout ?

Thank you !

Answer

The positive Button won't actually be created until the Dialog is shown. Since you're in a DialogFragment, you're not handling the show() call on the Dialog directly. You could set an OnShowListener on the AlertDialog, but it's probably simpler to just get the Button in the DialogFragment's onStart() method.

@Override
public void onStart() {
    super.onStart();

    positiveButton = ((AlertDialog) getDialog()).getButton(AlertDialog.BUTTON_POSITIVE);
    ...
}