String doesn't compare - android

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 &&

Related

Check if a string is alphanumeric

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");
}
}
});

ArrayList.indexOf() is not recognizing Objects

I have a ParseObject subclass , but everytime I want to get index of it it returns 0 so mListSectionPos returns an array of zero's (hachCode and equals methd implemented thanks to Apache Commons Utils).
It should be String.valueOf(mListItems.indexOf(beer_section)), but instead I'm using mListSectionPos.add(mListItems.indexOf(current_item) - 1); because it's working (more or less). Sometimes it cracks on getCurrentSectionPosition() that also works on indexOf() method.
So my question is: why indexOf() always return 0 in this piece of code?
It's based on https://github.com/bhavyahmehta/ListviewFilter - just adapted for ParseObject lists. Code below is my adaptation of his MainActivity.java that can be found here:
#Override
protected Void doInBackground(ArrayList<PiwoSubclass>... params) {
mListItems.clear();
mListSectionPos.clear();
ArrayList<PiwoSubclass> items = params[0];
if(mItems != null) {
if (mItems.size() > 0) {
String prev_section = "";
for (PiwoSubclass current_item : items) {
if (isCancelled()) break;
String current_section = current_item.getBeerName().substring(0, 1).toUpperCase(Locale.getDefault());
if (!prev_section.equals(current_section)) {
PiwoSubclass beer_section = null;
beer_section = new PiwoSubclass();
beer_section.setBeerName(current_section);
Log.i("ASD-current", beer_section.getBeerName());
mListItems.add(beer_section);
mListItems.add(current_item);
// array list of section positions
mListSectionPos.add(mListItems.indexOf(current_item) - 1); // that want works although it's way around
// TODO why is that error?
Log.i("ASD-listSectionSize", String.valueOf(mListItems.indexOf(beer_section)));
prev_section = current_section;
} else {
mListItems.add(current_item);
}
}
}
}
return null;
}
PiwoSubclass
public class PiwoSubclass extends ParseObject {
private String objectIdP;
private String marka;
private String marka_lowercase;
public PiwoSubclass() {
}
public String getObjectIdfromParse() {
return this.getObjectId();
}
public String getMarka(){
return this.getString("marka");
}
public String getBrewery(){
return this.getString("brewery");
}
public String getBeerName(){
return this.getString("beer_name");
}
public String getMarka_lowercase() {
return this.getString("marka_lowercase");
}
public void setMarka(String value){
put("marka", value);
}
public void setBeerName(String value){
put("beer_name", value);
}
public void setMarka_lowercase(String value){
put("marka_lowercase", value);
}
#Override
public int hashCode() {
return new HashCodeBuilder(17, 31) // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
.append(getObjectIdfromParse())
.toHashCode();
}
#Override
public boolean equals(Object obj) {
//return super.equals(obj);
if (!(obj instanceof PiwoSubclass))
return false;
if (obj == this)
return true;
marka_lowercase = getMarka_lowercase();
PiwoSubclass rhs = (PiwoSubclass) obj;
//Log.i("ASD-subclass", marka + "/" + rhs.getMarka());
return new EqualsBuilder()
// if deriving: appendSuper(super.equals(obj)).
.append(marka_lowercase, rhs.getMarka_lowercase())
.isEquals();
}
Now I have IndexOutOfBounds exception from PinnedHeaderAdapter:
public int getCurrentSectionPosition(int position) {
//String listChar = mListItems.get(position).getBeerName().substring(0, 1).toUpperCase(Locale.getDefault());
PiwoSubclass ps = mListItems.get(position); // TODO errorrrrrrrrr
return mListItems.indexOf(ps);
}
First, you check for mItems
if(mItems != null) {
if (mItems.size() > 0) {
but then you work with items
for (PiwoSubclass current_item : items) {
/* ... */
}
and ignore mItems for the rest of the method. I don't see any connection between these two.
It seems indexOf() doesn't return 0 but 1, otherwise you would get an ArrayList full of -1s
mListSectionPos.add(mListItems.indexOf(current_item) - 1);
I guess, somehow you always check for the first current_item, which is the second element in mListItems. If you would check for the beer_section - as it does for current_section in the original code - the code would work as expected.
After looking into ArrayList.indexOf(), the most likely reason is your PiwoSubclass.equals() method compares always equal to the first non-section element, because it hasn't set a beer name or some similar condition.
So, fixing the equals method might work as well.

Settings Non-English language password on android phone?

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);
}

How to validate date in dd/mm/yyyy format in editext in android?

I have two edittexts. I want to validate date entered in first edittext when I switch to next edittext... Is it possible?
I want to validate in dd/mm/yyyy format strictly..
please help me..
i searched and tried also but not get such a solution..
Step 1
youredittextname.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Is_Valid_date(name); // pass your EditText Obj here.
}
});
Step 2
Write a function.
public void Is_Valid_date(EditText edt) throws NumberFormatException {
if (edt.getText().toString().length() <= 0) {
edt.setError("Accept number Only.");
valid_name = null;
} else if (check your date format using simpledate format) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
}
If you need to know Validate of the date.
Please visit this link.
http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression/
Thank you.
private static final String DATE_PATTERN="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)";
private Pattern pattern= Pattern.compile(DATE_PATTERN);
public boolean isValidDate(final String date) {
Matcher matcher = pattern.matcher(date);
if (matcher.matches()) {
matcher.reset();
if (matcher.find()) {
String day = matcher.group(1);
String month = matcher.group(2);
int year = Integer.parseInt(matcher.group(3));
if (date.equals("31") && (month.equals("4")
|| month.equals("6")
|| month.equals("9")
|| month.equals("11")
|| month.equals("04")
|| month.equals("06")
|| month.equals("09"))) {
return false;
} else if (month.equals("2") || month.equals("02")) {
if (year % 4 == 0) {
if (day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
} else {
if (day.equals("29") || day.equals("30") || day.equals("31")) {
return false;
} else {
return true;
}
}
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
Use interface TextWatcher in Android. You have to override its methods:
In onTextChanged() limit the length of text
In afterTextChanged() use some good regular expression for date validation. It will be available from Google.
SimpleDateFormat can be of your help. You can look for tutorials or else visit here

Validating multiple EditTexts

Been stuck on this all night and there just doesn't seem to be an easy solution to it. I'm trying to validate all 4 of my fields to ensure that there is a value in each one of them, if there's a value in each one of them after I click the Calculate button a total will be calculated. If any of them don't have a value in them it'll return an error at every EditText which doesn't have a value and a total will not be calculated.
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if( eLoan.getText().toString().length() == 0 )
{
eLoan.setError( "A value is required" );
}
else if( eWage.getText().toString().length() == 0 )
{
eWage.setError( "A value is required" );
}
else if( eGrant.getText().toString().length() == 0 )
{
eGrant.setError( "A value is required" );
}
else if( eOther.getText().toString().length() == 0 )
{
eOther.setError( "A value is required" );
}
else
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
});
I can't get my head around it, I've tried to incorporate a boolean statement to check each EditText but it didn't work either. I'm convinced there's an easier method to do this.
I'm quite new to android, self teaching myself it so I would appreciate it if people could advise me on what I'm doing wrong and maybe give me an example of what I should do.
Thanks to all who respond.
Just to build on what others have said. You can do something like this...
Make a validation method that loops through your EditTexts, checks if they're empty, if true set error and then returns true or false...
public boolean validateEditText(int[] ids)
{
boolean isEmpty = false;
for(int id: ids)
{
EditText et = (EditText)findViewById(id);
if(TextUtils.isEmpty(et.getText().toString()))
{
et.setError("Must enter Value");
isEmpty = true;
}
}
return isEmpty;
}
Make a list of you EditText id's..
int[] ids = new int[]
{
R.id.section1_item1_textfield,
R.id.section1_item2_textfield,
R.id.section1_item3_textfield
};
Now use your validation method to check if empty...
if(!validateEditText(ids))
{
//if not empty do something
}else{
//if empty do somethingelse
}
To use the method above you will need to...
import android.text.TextUtils;
The good thing about doing it this way is that you can simply chuck all of your EditTexts into the list and it does the rest for you. Maintaining a huge chunk of if statements can be annoying and time consuming.
I think the problem is you're missing curlies at the last else, where the logic sits. As it is right now, only convertToString(); is part of that last else and the last four statements will execute no matter what error you're setting.
Try this:
cal.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
boolean failFlag = false;
// TODO Auto-generated method stub
if( eLoan.getText().toString().trim().length() == 0 )
{
failFlag = true;
eLoan.setError( "A value is required" );
}
if( eWage.getText().toString().trim().length() == 0 )
{
failFlag = true;
eWage.setError( "A value is required" );
}
if( eGrant.getText().toString().trim().length() == 0 )
{
failFlag = true;
eGrant.setError( "A value is required" );
}
if( eOther.getText().toString().trim().length() == 0 )
{
failFlag = true;
eOther.setError( "A value is required" );
}
// if all are fine
if (failFlag == false) {
convertToString();
converToDouble();
inTotal = inLoan + inWage + inGrant + inOther;
DecimalFormat currency = new DecimalFormat(".00");
TotalInNum.setText("£" + currency.format(inTotal));
}
}
});
This code will set more than one error, if more exist. Yours will signal only the first found error.
I think the best way to solve this problem is the example below:
private boolean verifyIfEditTextIsFilled(EditText... editText) {
boolean result = true;
for (EditText text : editText) {
if (text.getText().toString().isEmpty()) {
final View focusView = text;
text.setError(getString(R.string.error_required));
focusView.requestFocus();
result = false;
}
}
return result;
}
late answer But may Help someone in need.
Simplest way -->
Create method as below
public Boolean validateUserInput()
{
Boolean isAnyFieldsEmpty=false;
if (position.getText().toString()==null || position.getText().toString().equalsIgnoreCase(""))
{
position.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
position.setError(null);
isAnyFieldsEmpty=false;
}
if (eligiblity.getText().toString()==null || eligiblity.getText().toString().equalsIgnoreCase(""))
{
eligiblity.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
eligiblity.setError(null);
isAnyFieldsEmpty=false;
}
if (skillsRequired.getText().toString()==null || skillsRequired.getText().toString().equalsIgnoreCase(""))
{
skillsRequired.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
skillsRequired.setError(null);
isAnyFieldsEmpty=false;
}
if (desc.getText().toString()==null || desc.getText().toString().equalsIgnoreCase(""))
{
desc.setError("Empty postion");
isAnyFieldsEmpty=true;
}
else{
desc.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewFrmDate.getText().toString()==null || interviewFrmDate.getText().toString().equalsIgnoreCase(""))
{
interviewFrmDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewFrmDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToDate.getText().toString()==null || interviewToDate.getText().toString().equalsIgnoreCase(""))
{
interviewToDate.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToDate.setError(null);
isAnyFieldsEmpty=false;
}
if (interviewToTime.getText().toString()==null || interviewToTime.getText().toString().equalsIgnoreCase(""))
{
interviewToTime.setError("choose date");
isAnyFieldsEmpty=true;
}else{
interviewToTime.setError(null);
isAnyFieldsEmpty=false;
}
return isAnyFieldsEmpty;
}
Now on your Button click
call that method as below and validate
#overide
public void onclick
{
Boolean isinputEmpty=validateUserInput()
if(isinputEmpty==false)
{
///process your save or whatever processing it is
}
}

Categories

Resources