Limit EditText to text (A-z) only - java

I want an editText that only allows text input from A to z, no numbers or other characters. I've found out I have to use InputFilter but I don't understand how this code works.
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});

The code you posted adds a custom filter to the EditText field. It checks to see if the character entered is not a number or digit and then, if so, returns an empty string "". That code is here:
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
For your needs, you want to change the code slightly to check if the character is NOT a letter. So, just change the call to the static Character object to use the isLetter() method. That will look like this:
if (!Character.isLetter(source.charAt(i))) {
return "";
}
Now, anything that is not a letter will return an empty string.

Haven't actually done it, but check Androids NumberKeyListener. You can find the source code for it here:
http://www.java2s.com/Open-Source/Android/android-core/platform-frameworks-base/android/text/method/NumberKeyListener.java.htm
it does exactly the opposite of what you need, but that should be a good enough starting point.

Related

Limit Decimal Places in EditText

I'm using an EditText Field where the user can specify an amount of money.
I set the inputType to numberDecimal which works fine, except that this allows to enter numbers such as 123.122 which is not perfect for money.
I wrote some custom InputFilter method and it's working like this .User can 5 elements before dot and after dot-two,but not working correctly
My goals are :
1) use should input maximum 9999.99
2) If user starting from 0 and second element is also 0,It must replace with .(for example 0.0) and after two elements after dot(like this 0.01)
here is a my code
public class DecimalDigitsInputFilter implements InputFilter {
Pattern mPattern;
public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
mPattern=Pattern.compile("[0-9]*" + (digitsBeforeZero-1) + "}+((\\.[0-9]*" + (digitsAfterZero-1) + "})?)||(\\.)?");
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
Matcher matcher=mPattern.matcher(dest);
if(!matcher.matches())
return "";
return null;
}
}
I'm calling this method like this
amountValue.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});
How I can rewrite my code to solved my issues ?
thanks
Your constructed regex is all wrong.
The first part of your regex is this expression:
"[0-9]*" + (digitsBeforeZero-1) + "}+"
Say digitsBeforeZero = 5, that gets you:
[0-9]*4}+
That's not the correct regex. The regex is supposed to be:
[0-9]{1,5}
meaning between 1 and 5 digits.

How to limit the EditText input only allow 3 digits of number either integer or decimal

As the title says, I set up an EditText in my activity and want to limit the input to only numbers. However, it doesn't matter if it is a decimal number or integer. I do require the number of digits is limited at 3. For example, the input of '123', '1.23', '12.3' are all legit input.
'1234', '123.', '.123' are all illegal input.
I have tried to set up
android:inputType = "numberDecimal"
in the xml file.
And set the max length to 4.
edit:
I also tried following code:
InputFilter filter = new InputFilter() {
//^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$
//^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
// adding: filter
// build the resulting text
String destinationString = dest.toString();
String resultingTxt = destinationString.substring(0, dstart) + source.subSequence(start, end) + destinationString.substring(dend);
// return null to accept the input or empty to reject it
return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,2}\\.\\d{0,1}|\\d{0,1}\\.\\d{0,2})$") ? null : "";
}
return null;
}
};
I did modified the regex from the sample code mentioned by #Suman Dash.
My understanding of the regex
^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
is to allow certain pattern of number input such as #.##, ##.# and ###.
When I test the code, the pattern #.## and ##.# are working fine, but the pattern ### also allow input like ".##", for example, ".88" as legit input. And it treats the decimal point as a legit number, so I can only input ".88", not ".123". Anyway, I don't want any number starts with the decimal point.
How can I eliminate that?
What's the best way to achieve this goal? Thanks!
InputFilter filter = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; ++i)
{
if (!Pattern.compile("[1234567890\.]*").matcher(String.valueOf(source.charAt(i))).matches())
{
return "";
}
}
return null;
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText ntxt =(EditText)findViewById(R.id.numberEditTextbox) ;
ntxt.setFilters(new InputFilter[]{filter,new InputFilter.LengthFilter(4)});
}
This code may help you.

Show only English characters when editing text in EditText in Android

I have 3 languages on my keyboard in android device and I want to show only English language letters and numbers when starting to edit text inside EditText like username field , I tried to use this line in xml file for Edittext but without any result.
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
the best way is to use inputfilter and set it to your editText you can see a workaround to do that here :
How do I use InputFilter to limit characters in an EditText in Android?
also i found a code snippet to this like below:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend)
{
for (int i = start; i < end; i++) {
if (!isEnglishOrHebrew(source.charAt(i))) {
return "";
}
}
return null;
}
private boolean isEnglishOrHebrew(char c) {
. . .
}
};
edit.setFilters(new InputFilter[]{filter});

Making a substring out of a line read from file

So I am trying to read through a .txt file and find all instances of html tags, push opening tags to a stack, and then pop it when I find a closing tag. Right now I am getting String out of bounds exception for the following line:
if(scan.next().startsWith("</", 1))
{
toCompare = scan.next().substring(scan.next().indexOf('<'+2), scan.next().indexOf('>'));
tempString = htmlTag.pop();
if(!tempString.equals(toCompare))
{
isBalanced = false;
}
}
else if(scan.next().startsWith("<"))
{
tempString = scan.next().substring(scan.next().indexOf('<'+1), scan.next().indexOf('>'));
htmlTag.push(tempString);
}
It is telling me that the index of the last letter is -1. The problem I can think of is that all of the scan.next() calls are moving onto the next string. If this is the case, do I need to just write
toCompare = scan.next()
and then so my comparisons?
You have two major problems in your code:
you're calling scan.next() way too much and as you expect, this will move the scanner to the next token. Therefore, the last one will be lost and gone.
.indexOf('<'+2) doesn't return the index of '<' and adds 2 to that position, it will return the index of '>', because you're adding 2 to the int value of char < (60; > has 62). Your problem with index -1 ("It is telling me that the index of the last letter is -1.") comes from this call: .indexOf('<'+1) this looks for char '=' and if your string doesn't contain that, then it will return -1. A call for #substring(int, int) will fail if you pass -1 as the starting position.
I suggest the following two methods to extract the value between '<' and '>':
public String extract(final String str) {
if (str.startsWith("</")) {
return extract(str, 2);
} else if (str.startsWith("<")) {
return extract(str, 1);
}
return str;
}
private String extract(final String str, final int offset) {
return str.substring(str.indexOf('<') + offset, str.lastIndexOf('>'));
}
As you can see, the first method evaluates the correct offset for the second method to cut off either "offset. Mind that I wrote str.indexOf('<') + offset which behaves differently, than your str.indexOf('<' + offset).
To fix your first problem, store the result of scan.next() and replace all occurrences with that temporary string:
final String token = scan.next();
if (token.startsWith("</")) { // removed the second argument
final String currentTag = extract(token); // renamed variable
final String lastTag = htmlTag.pop(); // introduced a new temporary variable
if (!lastTag.equals(currentTag)) {
isBalanced = false;
}
}
else if (token.startsWith("<")) {
htmlTag.push(extract(token)); // no need for a variable here
}
I guess this should help you to fix your problems. You can also improve that code a little bit more, for example try to avoid calling #startsWith("</") and #startsWith("<") twice.

Is there such thing as math.substring in java?

Okay, I'm just getting curious. But I was wondering if there was such thing as a substring for numbers (math.substring ?), and then it would get the character(s) in the position specified.
Example (really poorly thought out one)
int number = 5839;
int example = number.substring(0,1)
println = example;
and then it displays 5?
Why don't you just convert it to a string, and then call substring(0,1)?...
int number = 5839;
int example = Integer.parseInt((number+"").substring(0,1));
Where calling number+"" causes the JVM to convert it into a String, and then it calls substring() on it. You then finally parse it back into an int
int number = 5839;
String numString = Integer.toString(number);
String example = numString.substring(0,1)
int subNum = Integer.parseInt(example);
System.out.println(subNum);
Change it to a String first.
Here's a little function I wrote:
public static int intSubstring(int number, int beginIndex, int endIndex) {
String numString = Integer.toString(number);
String example = numString.substring(beginIndex,endIndex)
int subNum = Integer.parseInt(example);
return subNum;
}
Or compressed:
public static int intSubstring(int number, int beginIndex, int endIndex) {
return Integer.parseInt((number+"").substring(beginIndex,endIndex));
}
No there is not. But you could possibly convert the integer to string and get the substring and again parse back to integer
No there no such thing, but you can do the following:
String s = ""+number; //You can now use the Substring method on s;
Or if you just want to remove the last y digits:
number = (int)(number/y);
of if you want to keep only the last z digits:
number = number%(Math.pow(10,z)); // % means modulo
No, there is none. int is a primitive data type. You can however, accomplish your need with one statement.
Integer.parseInt(String.valueOf(12345).substring(1, 2))

Categories

Resources