Deepak Deepak - 2 months ago 13
Android Question

How to use spinner and fill it from array in android

I'm a newbie in Android Development and I want to implement

Spinner
. My problem is that I have an array which has 9 values for a key Category. My array looks like:

MyArray
[{Category=Things To Do},
{Category=Transportation},
{Category=Food and Drink},
{Category=Accommodation},
{Category=Shopping},
{Category=Money and Costs},
{Category=Business},
{Category=Turkey Tour},
{Category=Events}]


I want to get value of category key. i need MyArray for spinner as bellow:

MyArray
{
Things To Do
Transportation
Food and Drink
Accommodation
Shopping
......
}


It is similar to iPhone code.

// iPhone code
for(int i=0; i<[arrayCategory count]; i++)
{
NSString *strSubTitle=[[arrayCategory objectAtIndex:i]objectForKey:@"category"];
}


Any idea?

Please help me.

Thanks

Answer

first create a xml in string for your String array

<?xml version="1.0" encoding="utf-8"?>
 <resources>
    <string name="planet_prompt">Choose a planet</string>
   <string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
   </string-array>
</resources>

then use the above xml for string array in your code like below

   @Override
     public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    Spinner spinner = (Spinner) findViewById(R.id.spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
        this, R.array.planets_array, android.R.layout.simple_spinner_item);
     adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
     spinner.setAdapter(adapter);
  }
Comments