Reputation: 3266
I have an edit text in my android application and I want to avoid from the user to enter an input when the string length in bytes reaches to the limit. It works fine in english, but not in hebrew.
The limit is 256, so when the input is in hebrew, I can insert only 128 characters. The problem is while I insert hebrew letters with punctuation. Lets say that I insert a dot, which is 1 byte, it allows me to enter more than 128 characters , even when the characters are only hebrew letters and punctuation.
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = s.toString().getBytes().length;
if (length == bytes_limit)
{
str = s.toString();
}
else if (length > bytes_limit)
{
input.setText(str);
input.setSelection(str.length());
}
}
Update:
String example: "שלום, מה שלומך"
Update 2:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = s.toString().getBytes().length;
if (length <= bytes_limit)
{
str = s.toString();
}
else if (length > bytes_limit)
{
input.setText(str);
input.setSelection(str.length());
}
}
Upvotes: 0
Views: 691
Reputation: 998
Try specifying the charset eg
int length = s.toString().getBytes("UTF-8").length;
replacing UTF-8 with the character set that you need
See
bytes of a string in java? And
Will String.getBytes("UTF-16") return the same result on all platforms?
Upvotes: 1
Reputation:
Punctuations are characters too, you write them in addition to the hebrew letter you want to write (if i am not wrong, you can add them with ALT + XXXX).
They are character like any others so when you write them, you are adding characters.
A dot(.) doesn't have punctuation so it takes only one byte.
To solve it, you can remove all of the punctuatuion.
You can create a function to ignore all the punctuation:
private String removePunctuation(String s)
{
for(int i = 0; i < s.length(); i++)
{
if(!(s.charAt(i) <= 'ת' && s.charAt(i) >= 'א'))
{
s = s.substring(0,i) + s.substring(i+1);
}
}
return s;
}
note the it will delete all of the punctuation, including -
and :
and so on...
You can add exceptions to the condition, enabling '-' or others.
Good luck :)
Upvotes: 0