0

I would like to start an activity only if the string I pass with putExtra from another activity equals 'search' like so:

        action = intent.getStringExtra("cause");
        Button btnBack = findViewById(R.id.btnBack);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(action == "search") {
                    Intent intent2 = new Intent(profiloutente.this, ricerca.class);
                    startActivity(intent2);
                }

            }
        });

But, the condition always seems to be false (so the activity doesn't start) even if the variable containing the get Extra equals "search". I don't understand why this happens. Could someone help me?

Conta
  • 236
  • 1
  • 6
  • 21

2 Answers2

1
if(action.equals("search"))

instead

if(action == "search") 
from56
  • 3,976
  • 2
  • 13
  • 23
1

The obvious probklem is that you are using == on a String. How do I compare strings in Java?

Another problem is that action is read outside of listener. That may be the intent, but I can't tell in isolation - if it is the surrounding the entire listener in the if statement would make more sense. action will take the value from getStringExtra at the time you run the surrounding code, not when the listener is fired.

There may be other issues.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305