0

I am making a simple password application now.

Something like I did in VB.

I have my code

package com.example.password;
import android.widget.*;

import com.example.password.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
    Button btn1;
    EditText et1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.button1);
        et1 = (EditText) findViewById(R.id.editText1);
    btn1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        if ("u" == et1.getText().toString()){
            Toast.makeText(MainActivity.this, "Yay!! GOOD GUESS", Toast.LENGTH_LONG ).show();

        }

    }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; his adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

No compilation or runtime errors, but I get no Toast popup when I get the "password" right.

A--C
  • 36,351
  • 10
  • 106
  • 92

1 Answers1

4

Change

if ("u" == et1.getText().toString())

to

if ("u".equals(et1.getText().toString()))

You can also do

if (et1.getText().toString().equals("u"))

but I believe the first way is safer against NPE but if you check for null then it doesn't really matter. The way you are currently doing it checks that they reference the same object. Using .equals("string") checks that the values are equal, when dealing with String

Java String function

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • THANKS A BUNCH! so should I always use this method? – user2130068 Mar 04 '13 at 02:51
  • When checking for equality of value for `String`s, yes!. As I put in my edit, your way checks to see if they are the same object but not necessarily the same value. You are welcome a BUNCH! :) – codeMagic Mar 04 '13 at 02:52
  • 1
    props for your first way to avoid the NPE. I would say stick with that – ElefantPhace Mar 04 '13 at 02:53
  • 1
    @ElefantPhace thanks! Although, I don't use it as much (shhhh!) because it doesn't feel natural to me so I make sure to check for `null`s when I need to but I probably should use it more since I know its better. :O – codeMagic Mar 04 '13 at 02:55
  • @user2130068 if this works for what you need, you may kindly accept the answer so others with the same issue can find the answer easier – codeMagic Mar 04 '13 at 03:15