I have a value from the selected item in spinner passed to a String variable 'selectedSpinner' using spinner.setOnItemSelectedListener()
. I am trying to access 'selectedSpinner' outside of the method.
I have tried to assign 'selectedSpinner' to another String 'selectedCategory' but outside of the spinner.setOnItemSelectedListener()
method, 'selectedSpinner' could not be resolved. What should be done to access 'selectedSpinner' outside of the method? Thanks
private void recordDialog() {
...
//get category
final Spinner spinner = subView.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedSpinner = parent.getItemAtPosition(position).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final String selectedCategory = selectedSpinner;
...
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
You need to declare selectedSpinner
outside recordDialog
function (or set it as global)
String selectedSpinner;
...
private void recordDialog() {
......
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedSpinner = parent.getItemAtPosition(position).toString();
}
}
After that you can assign selectedSpinner
to selectedCategory
.