I'm trying to check if a string is alphanumeric or not. I tried many things given in other posts but to no avail. I tried StringUtils.isAlphanumeric(), a library from Apache Commons but failed. I tried regex also from this link but that too didn't worked. Is there a method to check if a string is alphanumeric and returns true or false according to it?
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = fullnameet.getText().toString();
String numRegex = ".*[0-9].*";
String alphaRegex = ".*[A-Z].*";
if (text.matches(numRegex) && text.matches(alphaRegex)) {
System.out.println("Its Alphanumeric");
}else{
System.out.println("Its NOT Alphanumeric");
}
}
});
If you want to ascertain that your string is both alphanumeric and contains both numbers and letters, then you can use the following logic:
.*[A-Za-z].* check for the presence of at least one letter
.*[0-9].* check for the presence of at least one number
[A-Za-z0-9]* check that only numbers and letters compose this string
String text = fullnameet.getText().toString();
if (text.matches(".*[A-Za-z].*") && text.matches(".*[0-9].*") && text.matches("[A-Za-z0-9]*")) {
System.out.println("Its Alphanumeric");
} else {
System.out.println("Its NOT Alphanumeric");
}
Note that we could handle this with a single regex but it would likely be verbose and possibly harder to maintain than the above answer.
Original from here
String myString = "qwerty123456";
System.out.println(myString.matches("[A-Za-z0-9]+"));
String myString = "qwerty123456";
if(myString.matches("[A-Za-z0-9]+"))
{
System.out.println("Alphanumeric");
}
if(myString.matches("[A-Za-z]+"))
{
System.out.println("Alphabet");
}
try this
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Pattern p = Pattern.compile("[^a-zA-Z0-9]");
boolean hasSpecialChar = p.matcher(edittext.getText().toString()).find();
if (!edittext.getText().toString().trim().equals("")) {
if (hasSpecialChar) {
Toast.makeText(MainActivity.this, "not Alphanumeric", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Its Alphanumeric", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Empty value of edit text", Toast.LENGTH_SHORT).show();
}
}
});
This is the code to check if the string is alphanumeric or not. For more details check Fastest way to check a string is alphanumeric in Java
public class QuickTest extends TestCase {
private final int reps = 1000000;
public void testRegexp() {
for(int i = 0; i < reps; i++)
("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
}
public void testIsAlphanumeric2() {
for(int i = 0; i < reps; i++)
isAlphanumeric2("ab4r3rgf"+i);
}
public boolean isAlphanumeric2(String str) {
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
return false;
}
return true;
}
}
While there are many ways to skin this cat, I prefer to wrap such code into reusable extension methods that make it trivial to do going forward. When using extension methods, you can also avoid RegEx as it is slower than a direct character check. I like using the extensions in the Extensions.cs NuGet package. It makes this check as simple as:
Add the https://www.nuget.org/packages/Extensions.cs package to your project.
Add "using Extensions;" to the top of your code.
"smith23#".IsAlphaNumeric() will return False whereas "smith23".IsAlphaNumeric() will return True. By default the .IsAlphaNumeric() method ignores spaces, but it can also be overridden such that "smith 23".IsAlphaNumeric(false) will return False since the space is not considered part of the alphabet.
Every other check in the rest of the code is simply MyString.IsAlphaNumeric().
Your example code would become as simple as:
using Extensions;
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = fullnameet.getText().toString();
//String numRegex = ".*[0-9].*";
//String alphaRegex = ".*[A-Z].*";
//if (text.matches(numRegex) && text.matches(alphaRegex)) {
if (text.IsAlphaNumeric()) {
System.out.println("Its Alphanumeric");
}else{
System.out.println("Its NOT Alphanumeric");
}
}
});
Related
In this I am trying to validate phone number . but even if i do enter correct number it wont verify. code is below
cont=(EditText)findViewById(R.id.editcontact);
final String MobilePattern = "[0-9]{10}";
btn_log=(Button)findViewById(R.id.button_log);
btn_log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String phn=cont.getText().toString();
if (!phn.matches(MobilePattern)) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
}
});
your regex is proper but you are using it in incorrect way, you need to compile your pattern before using it to match.
String patterntomatch ="[0-9]{10}";
Pattern pattern=Pattern.compile(patterntomatch);
Matcher matcher=pattern.matcher(phn);
if (!matcher.find()) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
} else {
//To get matching text you can use
String ans = phn.substring(matcher.start(), matcher.end());
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
first try
final String phn=cont.getText().toString().trim();
it will help you when your content contains any spaces.
try by changing below things
final String MobilePattern = "[0-9]";
.......
final String phn=cont.getText().toString().trim();
.........
if (!phn.matches(MobilePattern) || phn.length() != 10 ) {
Toast.makeText(LoginActivity.this, "Invalid Contact number", Toast.LENGTH_SHORT).show();
}
Here I am giving you two step simple solution, At the very first allow user only take the valid input.
So use in your XML.
android:digits="0123456789"
android:inputType="phone"
android:maxLength="10"
Hopefully you can easily can understand each line meaning. Secondly you can validate on button click like below is given.
tv_login.setOnClickListener(v -> {
if (!isValidMobile(etPhone.getText().toString())){
//Invalid Mobile Number
}else {
//Valid Mobile Number
}
});
private boolean isValidMobile(String phone) {
boolean check = false;
if (!Pattern.matches("[a-zA-Z]+", phone)) {
if (phone.length() < 10 || phone.length() > 10) {
check = false;
} else {
check = true;
}
} else {
check = false;
}
return check;
}
I have 2 buttons for the quality. If the quality is set by typing first, the buttons work well, but if I don't write any quantity and I want to set it by plus button, the app crash.
increaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
quantity.setText(String.valueOf(givenQuantity + 1));
}
});
decreaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
//To validate if quantity is greater than 0
if ((givenQuantity - 1) >= 0) {
quantity.setText(String.valueOf(givenQuantity - 1));
} else {
Toast.makeText(EditorActivity.this, R.string.quantity_no_less_then_0, Toast.LENGTH_SHORT).show();
return;
}
}
});
Surround all your parsing lines with try/catch, like:
try {
givenQuantity = Integer.parseInt(textQuantity);
} catch (NumberFormatException e) {
e.printStackTrace();
givenQuantity = 0;
}
when the EditText is empty, a NumberFormatException is thrown because an empty string can not be parsed to int.
check is edittext is empty or not. If empty show toast message to user asking to enter some value to calculate.
I have a method where i compare two string, but they dont compare the right way. For example I have this:
dropdown.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
String selectedRate = data[i];
if (!data[i].equals("")) {
showSubQuestion(selectedRate);
} else {
selectedRate = "";
}
where data[i] is also and string and then it continues to:
showSubQuestion(String selectedValue){
...
String selectedValueId = selectedValue;
if (selectedValueId.equals("2459") && selectedValueId.equals("2460")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("2");
myTextViews[j].setText(surveyArray[0].getQuestions()[1].getText());
}
if (selectedValueId.equals("2461") && selectedValueId.equals("2462")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("3");
myTextViews[j].setText(surveyArray[0].getQuestions()[2].getText());
} else {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("4");
myTextViews[j].setText(surveyArray[0].getQuestions()[3].getText());
}
}
where selected value is ex: 2461 but it doesnt enters i the secont IF.
What am I doing wrong?
Here's part of the JSON:
"question_choices":[
{
"id":2459,
"label":"10 - highly likely",
"value":"10"
},
{
"id":2460,
"label":"9",
"value":"9"
},
{
"id":2461,
"label":"8",
"value":"8"
String selectedValueId = selectedValue;
if (selectedValueId.equals("2459") || selectedValueId.equals("2460")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("2");
myTextViews[j].setText(surveyArray[0].getQuestions()[1].getText());
}
if (selectedValueId.equals("2461") || selectedValueId.equals("2462")) {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("3");
myTextViews[j].setText(surveyArray[0].getQuestions()[2].getText());
} else {
surveyArray[0].getQuestions()[i].getQuestion_order_id().equals("4");
myTextViews[j].setText(surveyArray[0].getQuestions()[3].getText());
}
}
Replace this code & Try this out it will work
Your conditions are incorrect
if (selectedValueId.equals("2461") && selectedValueId.equals("2462"))
you should replace && with ||
Your value can't be 2461 AND 2462 at the same time
May be you want to use || instead of &&
With Reference to this question on android stack, i have a solution to do which allows android phone to provide support for setting non-english language password.
My phones SRC is based on stock-android which is not allowing me to set password which is non-ascii standards like Hebrew.
Based from AOSP source code that handles the password input for lock screen, ChooseLockPassword.java, inside validatePassword() (line 292), here is a snippet that will show the "illegal character" message (from line 311):
// allow non control Latin-1 characters only
if (c < 32 || c > 127) {
return getString(R.string.lockpassword_illegal_character);
}
I have commented out this part but i don't think so this will work. [Waiting to be Flashed]
There are no such question for this condition, i need help for cracking the possibility for doing this any "Work around" will also do.
So after fighting few days i got a workaround by implementing my method for it.
private String validateHebrewPassword(String password)
{
if (password.length() < mPasswordMinLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
}
if (password.length() > mPasswordMaxLength) {
return getString(mIsAlphaMode ?
R.string.lockpassword_password_too_long
: R.string.lockpassword_pin_too_long, mPasswordMaxLength + 1);
}
for (int i = 0; i < password.length(); i++)
{
char c = password.charAt(i);
System.out.println("Validate Hebrew Password Success "+ " Char "+c+" for password "+password+ " langauage "+locale);
}
return null;
}
And modiying its validatePasswor() caller a bit specific to hebrew like:
private void handleNext() {
final String pin = mPasswordEntry.getText().toString();
if (TextUtils.isEmpty(pin)) {
return;
}
String errorMsg = null;
if (mUiStage == Stage.Introduction)
{
String locale = java.util.Locale.getDefault().getLanguage();
if(locale.equals("iw")) //Specific Hebrew check
{
errorMsg = validateHebrewPassword(pin); //New Method
}
else
{
errorMsg = validatePassword(pin); //AOSP Method
}
if (errorMsg == null)
{
mFirstPin = pin;
mPasswordEntry.setText("");
updateStage(Stage.NeedToConfirm);
}
} else if (mUiStage == Stage.NeedToConfirm) {
if (mFirstPin.equals(pin)) {
final boolean isFallback = getActivity().getIntent().getBooleanExtra(
LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
mLockPatternUtils.clearLock(isFallback);
mLockPatternUtils.saveLockPassword(pin, mRequestedQuality, isFallback);
getActivity().setResult(RESULT_FINISHED);
getActivity().finish();
} else {
CharSequence tmp = mPasswordEntry.getText();
if (tmp != null) {
Selection.setSelection((Spannable) tmp, 0, tmp.length());
}
updateStage(Stage.ConfirmWrong);
}
}
if (errorMsg != null) {
showError(errorMsg, mUiStage);
}
}
private void updateUi() {
String password = mPasswordEntry.getText().toString();
final int length = password.length();
if (mUiStage == Stage.Introduction && length > 0) {
if (length < mPasswordMinLength) {
String msg = getString(mIsAlphaMode ? R.string.lockpassword_password_too_short
: R.string.lockpassword_pin_too_short, mPasswordMinLength);
mHeaderText.setText(msg);
mNextButton.setEnabled(false);
} else
{
String locale = java.util.Locale.getDefault().getLanguage();
String error = null;
if(locale.equals("iw")) //Specific Hebrew check
{
error = validateHebrewPassword(password); //New method
}
else
{
error = validatePassword(password); //AOSP Method
}
if (error != null) {
mHeaderText.setText(error);
mNextButton.setEnabled(false);
} else {
mHeaderText.setText(R.string.lockpassword_press_continue);
mNextButton.setEnabled(true);
}
}
} else {
mHeaderText.setText(mIsAlphaMode ? mUiStage.alphaHint : mUiStage.numericHint);
mNextButton.setEnabled(length > 0);
}
mNextButton.setText(mUiStage.buttonText);
}
I'm getting this error in my code: java.lang.NumberFormatException.
m1 is for main string that contains the whole expression
s is for second number if no operator other than division is present
f is for first number if no operator other than division is present
f1 is for first number if operator other than division is also present
s1 is for second number if operator other than division is also present
Here is the code:
b12.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s="";
String f="";
String f1="";
String s1="";
int z=m1.length();
int pos,pos1;
for(int i=0;i<z;i++)
{
int m=m1.codePointAt(i);
//Checking for division
if(m==47)
{
// Loop to calculate second number
for(int j=i+1;j<z;j++)
{
int d=m1.codePointAt(j);
if(d!=43||d!=45||d!=42||d!=47)
{
s+=m1;
}
else
{ pos=j;
s1+=m1.substring(pos,z);
break;
}
}
// Loop to calculate first number
for(int j=i-1;j>=0;j--)
{
int d=m1.codePointAt(j);
if(d!=43||d!=45||d!=42||d!=47)
{
f+=m1;
}
else
{ pos1=j;
f1+=m1.substring(0,pos1);
break;
}
}
String rev=new StringBuffer(f).reverse().toString();
float ans=Float.parseFloat(rev)/Float.parseFloat(s);
String e=Float.toString(ans);
if(f1==""&&s1=="")
{
m1=""+e;
}
else
{
m1=""+f1+e+s1;
}
z=m1.length();
e1.setText(m1);
}
}
}
});
}
Potential code which can throw NumberFormatException :
float ans=Float.parseFloat(rev)/Float.parseFloat(s);
Check if rev and s can resolve to a valid float value . Also you can do the following :
float ans=Float.parseFloat(rev.trim())/Float.parseFloat(s.trim());
which will remove the leading and trailing whitespaces, if any.
Also if possible , replace StringBuffer with StringBuilder.