Tuesday, December 14, 2010

Fun With Text Filters


Creative Commons Licence

This work is licenced under a Creative Commons Licence.

In the Blackberry API the TextFilter, and its subclasses (EmailAddressTextFilter, FilenameTextFilter, HexadecimalTextFilter, IPTextFilter, LowercaseTextFilter, NumericTextFilter, PhoneTextFilter, URLTextFilter, and UppercaseTextFilter) provide useful input filtering for Blackberry programmers. Sometimes we want to quickly combine the function of two existing text filters into one. I have a project where I want the user to be able to input groups of upercase letters and numbers separated by spaces. Here is the quick hack I came up with:

import net.rim.device.api.ui.text.TextFilter;
import net.rim.device.api.system.Characters;

/**
* A TextFilter class to filter for station identifiers
*/
private static class StationFilter extends TextFilter {

 // Order of the supporting filters is important, NUMERIC will convert
 // letters to numbers if it gets them first.
 private static TextFilter[]      _tf = {
  TextFilter.get(TextFilter.NUMERIC),
  TextFilter.get(TextFilter.UPPERCASE)
 };

// Convert using the first supporting filter that has a conversion
 public char convert( char character, int status) {
  char c = 0;

  for (int i = _tf.length - 1; i >= 0; i--) {
   c = _tf[i].convert(character, status);
   if (c != 0) {
    return c;
   }
  }

  return 0;
 }

// Validate a space for separator, then by supporting filter
 public boolean validate(char character) {
  if (character == Characters.SPACE) {
   return true;
  }

  for (int i = _tf.length - 1; i >= 0; i--) {
   boolean b = _tf[i].validate(character);
   if (b) {
    return true;
   }
  }

  return false;
 }
}

1 comment: