What type of Object does Spinner.getItemAtPosition(...) return?

android, android-spinner, return-type, type-conversion

Solution

I assume the "parent" you are talking about is a Spinner. In this case:

Spinner.getItemAtPosition(pos); 

will always return the type of object that you filled the Spinner with.

An example using a CustomType: (the Spinner is filled with Items of type "CustomType", therefore getItemAtPosition(...) will return CustomType)

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
CustomType [] customArray = new CustomType[] { .... your custom items here .... };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, customArray);

spinner.setAdapter(adapter);  

CustomType type = (CustomType) spinner.getItemAtPosition(0); // it will return your CustomType so you can safely cast to it

Another example using a String Array: (the Spinner is filled with Items of type "String", therefore getItemAtPosition(...) will return String)

Spinner spinner = (Spinner) findViewById(R.id.spinner1);
String[] stringArray= new String[] { "A", "B", "C" };

// fill an arrayadapter and set it to the spinner
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, stringArray);

spinner.setAdapter(adapter);  

String item = (String ) spinner.getItemAtPosition(0); // it will return your String so you can safely cast to it

Problem

What will this statement return? ``` parent.getItemAtPosition(position) ``` Where `parent` is a parent view for a spinner and position is the selected position from the spinner view.

Original source