I need to validate selected item of Spinner
in Android
.
I tried the following code, but it's not working.
if (Spinner1.getSelectedItem().toString().trim() == "Pick one") {
Toast.makeText(CallWs.this, "Error", Toast.LENGTH_SHORT).show();
}
What is wrong with the code, and how can i fix it?
Simply use this.
Use
.equals
or.equalsIgnoreCase
to compare two strings injava/android
instead of==
.Try this
Try this..
==
always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.However, the
equals
method can be overridden - so two distinct objects can still be equal...... For more infoUse
equals("Pick one")
and always useequals()
method when checking for equality forString
type in Java (unless you are checking for reference equality) as follows;What's wrong with you code is; you are using
==
which results in checking ifSpinner1.getSelectedItem().toString()
is the same reference as"Pick one"
which will always be false since "Pick one" is anew String()
instanceFor details, check:
Create a new layout called spinner_item.xml:
inside your activity MainActivity.java initialize your spinner view:
Finally use the following method to validate your spinner: