Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android get all countries on array spinner

I've searched a lot but the stuff I found was a little confused.

I need to get the android country list and set default the user locale.

For example: I'm registering an user account and I need to insert the country, in that spinner will show all countries but by default will appear my default locale.

Right now I have:

private Spinner spCountry;
private String array_spinner[];

...

spCountry = (Spinner) findViewById(R.id.spCountry);

array_spinner = new String[1];
array_spinner[0] = "Portugal";

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_spinner);
spCountry.setAdapter(adapter);

Thank you all for the help!

like image 868
FilipeOS Avatar asked Sep 03 '13 13:09

FilipeOS


1 Answers

You can use

private static final String DEFAULT_LOCAL = "Portugal";

Then use it to set default selection as follows.

ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, array_spinner);
spCountry.setAdapter(adapter);
spCountry.setSelection(adapter.getPosition(DEFAULT_LOCAL));

OUTPUT:

enter image description here

UPDATE: Create arrays.xml in res/values

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string-array name="country_arrays">
        <item>Malaysia</item>
        <item>United States</item>
        <item>Indonesia</item>
        <item>France</item>
        <item>Italy</item>
        <item>Singapore</item>
        <item>New Zealand</item>
        <item>India</item>
        <item>Portugal</item>
    </string-array>

</resources>

Then use following in your activity to get all the countries.

array_spinner = getResources().getStringArray(R.array.country_arrays);
like image 79
Ritesh Gune Avatar answered Oct 15 '22 09:10

Ritesh Gune