0

I have the weirdest problem...

all I am trying to do is to get the value from a EditText and do some validation.

The value in the edittext must be between 1 and 10. However, even if I enter any number between 1 or 10 , it still validates false. I even tested the edittext input to make sure it is correct , and it is, but the if still fails . Any ideas ?

here is the code:

ed = (EditText) dialog2.findViewById(R.id.ed_quantity);                                                  
Button bq = (Button) dialog2.findViewById(R.id.alert_a);
dialog2.setCancelable(false);
dialog2.show();
bq.setOnClickListener(new OnClickListener(){

    @Override
    public void onClick(View v)
    {
        String test = ed.getText().toString();
        Toast toast23452234 = Toast.makeText(mContext, "Quantity: "+test, Toast.LENGTH_LONG);
        toast23452234.show();
        if(test=="1"||test=="2"||test=="3"||test=="4"||test=="5"||test=="6"||test=="7"||test=="8"||test=="9"||test=="10")
        {
            quantity = Integer.parseInt(ed.getText().toString());
            dialog2.dismiss();
            ed.setText("1");
        }
        else
        {
            Toast toast2345223 = Toast.makeText(mContext, "Quantity must be between 1 and 10" , Toast.LENGTH_LONG);
            toast2345223.show();
        }
    }
});
Pratik
  • 30,639
  • 18
  • 84
  • 159
Janpan
  • 2,164
  • 3
  • 27
  • 53

6 Answers6

1

try this

 test.trim().equalsIgnoreCase("1")

in your if-condition

techieWings
  • 2,045
  • 2
  • 16
  • 18
0

Use equals method to compare strings..

if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))

or use int to compare

int test = Integer.valueOf(ed.getText().toString());
Nermeen
  • 15,883
  • 5
  • 59
  • 72
0

String is not a native type so you can't do test=="1". This compares the object references and obviously the two objects have different references.

Call equals(Object object) method on string object. Like,

test.isEquals("1")

Better parse the input string to integer as

int testInteger = Integer.parseInt(test);

and compare as

if(testInteger==1 || testInteger ==2)

This saves many method calls to string object.

Supreethks
  • 597
  • 6
  • 16
0

use .equals("") in case of String.

if(test.equals("1")||test.equals("2")||test.equals("3")||test.equals("4")||test.equals("5")||test.equals("6")||test.equals("7")||test.equals("8")||test.equals("9")||test.equals("10"))
Kamal
  • 1,415
  • 13
  • 24
0

use .equals on string operation instead of ==

  if(test.equals("1")||... and so on) 

or else convert string into "int".

SKK
  • 5,261
  • 3
  • 27
  • 39
0

Use test.equals("1") || .....

You can also do this

int t = Integer.parseInt(test);
if(t == 1 || t == 2 || ...)
Android Killer
  • 18,174
  • 13
  • 67
  • 90