In my spinner, I have the values 'Male', 'Female' and 'Male and female'. If someone clicks 'Male' in the spinner, I'd like to retrieve that value. My existing code which uses spinner.getSelectedItem().toString() provides the following result:
com.example.kitchen.SpinnerItem@64dd10e
I've even tried to implement .setOnItemSelectedListener() but that didn't work either. Main activity code:
public class ManageEventsActivity extends AppCompatActivity {
String stringCreateEventGender;
ArrayList<String> arrayUpcomingEventGender = new ArrayList<>();
ArrayList<SpinnerItem> mGenderList = new ArrayList<>();
SpinnerAdapter genderAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manage_events);
spinnerCreateEventGender = findViewById(R.id.spinnerCreateEventGender);
initGenderList();
genderAdapter = new SpinnerAdapter(this, mGenderList);
spinnerCreateEventGender.setAdapter(genderAdapter);
}
private void initGenderList() {
mGenderList.add(new SpinnerItem("Male"));
mGenderList.add(new SpinnerItem("Female"));
mGenderList.add(new SpinnerItem("Male and female"));
}
}
Spinner adapter code:
public class SpinnerAdapter extends ArrayAdapter<SpinnerItem> {
public SpinnerAdapter(Context context, ArrayList<SpinnerItem> genderList) {
super(context, 0, genderList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.spinner_layout, parent, false
);
}
TextView textViewItem = convertView.findViewById(R.id.textViewItem);
SpinnerItem currentItem = getItem(position);
if (currentItem != null) {
textViewItem.setText(currentItem.getItem());
}
return convertView;
}
}
Spinner item code:
public class SpinnerItem {
String mItem;
public SpinnerItem(String item) {
mItem = item;
}
public String getItem() {
return mItem;
}
}
Managed to find a solution:
spinnerCreateEventGender.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinnerItem = (SpinnerItem) parent.getItemAtPosition(position);
clickedItem = spinnerItem.getItem();
Toast.makeText(ManageEventsActivity.this, clickedItem, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});