Question

The output is always not a girl. How do I compare the string amruta?

Plz tell me if the statement is fine.

I have used explicit intents and want to compare 2 strings.

Even if I enter "amruta" in editText field, I get not a girl.

package com.satish.explicitintents;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class Main extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText et = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(Main.this, Second.class); 
                intent.putExtra("thetext", et.getText().toString());
                startActivity(intent);
            }
        });
    }
}

-

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Second extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);
        TextView tv = (TextView) findViewById(R.id.textView1);
        if (getIntent().getExtras().getString("thetext")== "amruta")
        {
            tv.setText("girl");
        }
        else 
            tv.setText("not a girl");
    }
}
Was it helpful?

Solution

Use equals() method instead of == operator as below...

if (getIntent().getExtras().getString("thetext").equals( "amruta")) {

    tv.setText("girl");

} else {

    tv.setText("not a girl");

}

You can also use equalsIgnoreCase() method.

Instances of String are objects, so you can't compare two objects with == operator. The == operator is used to compare to primitive type data. To compare two String, you have to use equals() or equalsIgnoreCase() method.

OTHER TIPS

Using the == operator in java programming to compare two strings its a bad sign of programming. You need to use equals() or equalsIgnoreCase() methods. So use this:

if (getIntent().getExtras().getString("thetext").equalsIgnoreCase(amruta))
{
   tv.setText("girl");
}
 else {
   tv.setText("not a girl");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top