I need to restrict Android textInput to only ISO-8859-1 characters

Viewed 286

I have an input on my android app, the text from this input is sent to my server and then later retrieved by another front end to be displayed. the other front end can only work with ISO-8859-1 character set and will crash if any other characters are encountered(its an old software) so I need to restrict the EditText to only allow ISO-8859-1 characters and I'm not sure how I can achieve this.

[EDIT]
So big thanks to aarnaut for the help, this is what I have ended up with:

public class ISO_8859_1_InputFilter implements InputFilter {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        CharsetEncoder iso_8859_1 = Charset.forName("ISO_8859_1").newEncoder();
        if (source instanceof SpannableStringBuilder) {
            SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
            for (int i = end - 1; i >= start; i--) {
                char currentChar = source.charAt(i);
                if (!iso_8859_1.canEncode(currentChar)) {
                    sourceAsSpannableBuilder.delete(i, i + 1);
                }
            }
            return source;
        } else {
            StringBuilder filteredStringBuilder = new StringBuilder();
            for (int i = start; i < end; i++) {
                char currentChar = source.charAt(i);
                if (iso_8859_1.canEncode(currentChar)) {
                    filteredStringBuilder.append(currentChar);
                }
            }
            return filteredStringBuilder.toString();
        }
    }
}
1 Answers

You could simply prevent the user from entering anything other than what is allowed by the ISO-8859-1. You can do this by either applying an android:digits attribute to the EditText e.g

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "

or by implementing a custom filter whenever a new character is passed into the view. This will ensure that you have ISO-8859-1 characters only.

A class CharsetEncoder within java.nio.charset package provides possibility to check whether a string/character satisfies a specific encoding,

val encoder = Charset.forName("ISO_8859_1").newEncoder()
val canEncode = encoder.canEncode(text)
Related