I'm experiencing this on my code and I cannot figure out why. Basically I'm setting android:text to "0" on XML and when checking with getText if it's "0" it returns false. If I set it to 0 with setText and check again it returns true.
<TextView android:id="@+id/edit_text"
android:text="0" />
TextView calc = (TextView) findViewById(R.id.edit_text);
return( calc.getText() == "0" ); // false
----
calc.setText( "0" );
return( calc.getText() == "0" ); // true
Why does this happen? How can I check if calc.getText() is 0?
You never compare Objects (String
are a subclass of CharSequence
which is a subclass of Object
, and I'd recommend working with them instead of CharSequence
) with ==
, since that compares references, not actual Object content. All Objects have a equals()
method, but Strings defintely customize it (override) to implement a check for if the Strings to compare are the same.
Instead do calc.getText().toString().equals ("0");
So in terms of why it's happening - Android makes one Object then when you specify "0", you create another one. Using equals()
solves this because it checks the content first then gives a result (true/false).