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?
Use .equals
or .equalsIgnoreCase
to compare two strings in java/android
instead of ==
.
Try this
if (Spinner1.getSelectedItem().toString().trim().equals("Pick one")) {
Toast.makeText(CallWs.this, "Error", Toast.LENGTH_SHORT).show();
}
Use equals("Pick one")
and always use equals()
method when checking for equality for String
type in Java (unless you are checking for reference equality) as follows;
if (Spinner1.getSelectedItem().toString().trim().equals("Pick one")) {
Toast.makeText(CallWs.this, "Error", Toast.LENGTH_SHORT).show();
}
What's wrong with you code is; you are using ==
which results in checking if Spinner1.getSelectedItem().toString()
is the same reference as "Pick one"
which will always be false since "Pick one" is a new String()
instance
For details, check:
- string .equals() vs ==
- How to compare Strings
Create a new layout called spinner_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
inside your activity MainActivity.java initialize your spinner view:
Spinner mySpinner= (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.items_array, R.layout.spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
Finally use the following method to validate your spinner:
boolean validateSpinner(Spinner spinner, String error){
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
TextView selectedTextView = (TextView) selectedView;
if (selectedTextView.getText().equals("")) {
selectedTextView.setError(error);
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
return false;
}
}
return true;
}
Try this..
else if (Spinner1.getSelectedItem().toString().trim().equals("Pick one")) {
Toast.makeText(CallWs.this, "Error",
Toast.LENGTH_SHORT).show();
==
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 info
Simply use this.
else if (Spinner1.getSelectedItem().toString().trim().equalsIgnoreCase("Pick one")) {
Toast.makeText(CallWs.this, "Error",
Toast.LENGTH_SHORT).show();