How to get a string from the View object returned by the onItemSelected() method
The onItemSelected() method should return a View as one of its objects, in this case it is a textView, verified by getting the description and hash of the object in Logcat, so the View is actually a TextView. The method shown here returns a View
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
How do I get a text string stored in the View? For example, if you do,
view.getText();
It should return a string stored in a textView, but it doesn’t work
But I tried a lot of different methods like converting View to TextView to get the stored string from View, but none of those methods worked. One of my failed attempts went something like this
((TextView) view).getText()
How do I get a string from the View returned by the onItemSelected callback method?
The ArrayList loads the String and places it in the adapter shown here
public class SpinnerAdapter extends ArrayAdapter<String>{
ArrayList<String> objects;
Context context;
int textViewResourceId;
public SpinnerAdapter(Context context, int textViewResourceId, ArrayList<String> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.textViewResourceId = textViewResourceId;
this.objects = objects;
}
spinnerOne.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TODO Auto-generated method stub
Toast.makeText(StandardSelectionSettingsSmallTank.this, "id returned "+ Long.toString(id) , Toast.LENGTH_SHORT).show();
Toast.makeText(StandardSelectionSettingsSmallTank.this, "view returned "+ ((TextView) view).getText() , Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
TODO Auto-generated method stub
}
});
}
EDIT: I just tried the following code and it’s doing what I need to do. It gets the string stored in the current position of the spinner. The string I loaded earlier with ArrayList. This is valid, so I guess I’ll use it instead of using the View object returned by the onItemSelected method.
String
selection = spinnerOne.getSelectedItem().toString();
Unless someone knows how to do this otherwise by using the View object, I’ll use it
Solution
Tick this.
parent.getItemAtPosition(position).toString() in place of `((TextView) view).getText()`