- // Allow the `enter` key on the keyboard to create the domain from `add_domain_edittext`.
- EditText addDomainEditText = (EditText) alertDialog.findViewById(R.id.domain_name_edittext);
- addDomainEditText.setOnKeyListener(new View.OnKeyListener() {
- public boolean onKey(View view, int keyCode, KeyEvent event) {
- // If the event is a key-down on the `enter` key, select the `PositiveButton` `Add`.
- if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
- // Trigger `addDomainListener` and return the `DialogFragment` to the parent activity.
- addDomainListener.onAddDomain(AddDomainDialog.this);
- // Manually dismiss the `AlertDialog`.
- alertDialog.dismiss();
- // Consume the event.
- return true;
- } else { // If any other key was pressed, do not consume the event.
- return false;
+ // Initialize `domainsDatabaseHelper`. The two `nulls` do not specify the database name or a `CursorFactory`. The `0` specifies the database version, but that is ignored and set instead using a constant in `DomainsDatabaseHelper`.
+ final DomainsDatabaseHelper domainsDatabaseHelper = new DomainsDatabaseHelper(getContext(), null, null, 0);
+
+ // Get handles for the views in `alertDialog`.
+ final EditText addDomainEditText = alertDialog.findViewById(R.id.domain_name_edittext);
+ final TextView domainNameAlreadyExistsTextView = alertDialog.findViewById(R.id.domain_name_already_exists_textview);
+ final Button addButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
+
+ // Update the status of the warning text and the `add` button.
+ addDomainEditText.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ // Do nothing.
+ }
+
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ // Do nothing.
+ }
+
+ @Override
+ public void afterTextChanged(Editable s) {
+ if (domainsDatabaseHelper.getCursorForDomainName(addDomainEditText.getText().toString()).getCount() >0) { // The domain already exists.
+ // Show the warning text.
+ domainNameAlreadyExistsTextView.setVisibility(View.VISIBLE);
+
+ // Disable the `add` button.
+ addButton.setEnabled(false);
+ } else { // The domain do not yet exist.
+ // Hide the warning text.
+ domainNameAlreadyExistsTextView.setVisibility(View.GONE);
+
+ // Enable the `add` button.
+ addButton.setEnabled(true);