0

When I'm comparing an EditText's value with a String var in java, it is going to else part.

case 2 is not executing, every time default case is executing

sem=(EditText)findViewById(R.id.csem);
sem1=sem.getText().toString();

switch (sem1) {
    case "2":
        c = 1;
        i.putExtra("fees", c);
        startActivity(i);
        break;
    default:
       Toast.makeText(details.this, "Enter valid current sem", Toast.LENGTH_SHORT).show();
  break;
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Pratheek Reddy
  • 103
  • 1
  • 8

2 Answers2

1

Since it is a String, you should compare it using equals method

// Gets the value of the EditText
String value = ((EditText) findViewById(R.id.csem)).getText().toString();

if(value.equals("2")) {
    // Do your things
}
Hocine B
  • 391
  • 2
  • 8
0

switch statement on String objects is a new feature introduced in Java 1.7. Unfortunatelly Android requires version 1.6 or 1.5. This is why you have to forget for some time about such constructions.

You can avoid using if-statements-chain by storing the map of methods which will be executed for certain String: Map. You can always encapsulate Method it with some Handler object. Look here for more info: How to remove large if-else-if chain

and

why-cant-i-switch-on-a-string