Skip to content

Instantly share code, notes, and snippets.

@jdamcd
Last active December 12, 2015 10:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdamcd/4761834 to your computer and use it in GitHub Desktop.
Save jdamcd/4761834 to your computer and use it in GitHub Desktop.
Email adapter for AutoCompleteTextView that looks for emails from all account types, not just Google.
private static final String EMAIL_REGEX = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
private static final Pattern EMAIL_PATTERN = Pattern.compile(EMAIL_REGEX);
private ArrayAdapter<String> getEmailAddressAdapter(Context context) {
Account[] accounts = AccountManager.get(context).getAccounts();
HashSet<String> emailSet = new HashSet<String>();
for (int i = 0; i < accounts.length; i++) {
if (isEmailAddress(accounts[i].name)) {
emailSet.add(accounts[i].name);
}
}
String[] emailArray = emailSet.toArray(new String[emailSet.size()]);
return new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, emailArray);
}
private boolean isEmailAddress(String possibleEmail) {
return EMAIL_PATTERN.matcher(possibleEmail).matches();
}
@orrc
Copy link

orrc commented Feb 12, 2013

I recently discovered that Android already has an email regex built-in at android.util.Patterns#EMAIL_ADDRESS (though from Android 2.2+).

@jdamcd
Copy link
Author

jdamcd commented Feb 12, 2013

@orrc Neat. Had no idea that class existed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment