Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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