views:

338

answers:

2

I am trying to populate the text of a second EditText widget with the text from the first EditText widget only when the second EditText widget receives focus, the second widget is not empty, and the first widget is not empty.

I have the following OnFocusChangeListener handler code.

        public void onFocusChange(View v, boolean hasFocus) {

        EditText stxt = (EditText) findViewById(R.id.numberone);
        EditText etxt = (EditText) findViewById(R.id.numbertwo);


        if (hasFocus && stxt.getText().toString().trim() != "" && etxt.getText ().toString().trim() == "")
        {
            etxt.setText(stxt.getText().toString().trim());
        }
    }

When I run it and click into the second widget it does not populate. When I remove the third constraint ('etxt.getText ().toString().trim() == ""')) it works. so getText() on the second EditText widget is returning something even though the second widget has no initial value other then the text that is displayed via the hint attribute.

How can I accomplish this.

Thanks

+1  A: 

Never compare strings in Java with == or !=. Use equals(). Try that and see if you get better results.

CommonsWare
yes...I see now
+2  A: 

You should be doing an object comparison using String.equals(), not just x == "".

I would rewrite this using Android's handy TextUtils class:

String one = stxt.getText().toString();
String two = etxt.getText().toString();

if (hasFocus && TextUtils.getTrimmedLength(one) != 0 
      && TextUtils.getTrimmedLength(two) == 0) {
    etxt.setText(one);
}
Christopher