Check length of a String in Android
android, string
Solution
You will want to ensure that you handle a null string as well as ensuring your string is within the limits you want. consider:
text = et.getText().toString();
if (text == null || text.length() < 3 || text.length > 8) {
tv.setText("Invalid length, should be from 3 to 8 characters. Please check your code");
} else {
a = text.substring(0,1);
b = text.substring(1,2);
c = text.substring(3,4);
if (text.length() > 3) {
d = text.substring(4);
} else {
d = null;
}
}
Problem
I want to check whether the entered strings length is between 3 to 8 characters. Previously I used `if condition` and it worked. However when I introduced some substring from the string , one of the `if statements` doesnt work. Can some one help me to understand why. Thanks. My codes is Working Code: ``` text = et.getText().toString(); l = text.length(); a = text.substring(0, 1); if (l >=9) tv.setText("Invalid length!!! Please check your code"); if (l <= 2) tv.setText("Invalid length! Please check your code"); ``` And here, the second `if statement doesnt` work. ``` text = et.getText().toString(); l = text.length(); a = text.substring(0, 1); c = text.substring(1, 2); d = text.substring(3, 4); e = text.substring(4); if (l >=9) tv.setText("Invalid length!!! Please check your code"); if (l <= 2) tv.setText("Invalid length! Please check your code"); ```