Android add string array in xml file to spinner

A data source of a Spinner can be data fetched from a local SQLite or a remote Mysql database, an array of strings, an ArrayList object, or an string array defined in xml layout file. In this Android tip, I am going to show to how to define a string array in xml file and how to read items of the array to display in a Spinner widget.

Now to have an example application on populating items of an string array defined in xml file to the Spinner, you create a new Android project. Then in the res/values/strings.xml file, you define a string array using the <string-array> tag as shown below. You use the <item> tag to define an item of the string array. The name of the string array is array_countries. When you read items of the string array, its name is important.

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


   <string name="app_name">AndApp</string>
   <string name="hello_world">Hello world!</string>
   <string name="action_settings">Settings</string>
   <string-array name="array_countries">


In the res/layout/activity_main.xml file, you add a Spinner widget.

<RelativeLayout xmlns:android=""
   tools:context="com.example.myfirstprogram.MainActivity" >


A Spinner widget needs a layout file to renders its items. So, you need to create a layout file called spinner_layout.xml file in the res/layout directory. In the layout file, you add a TextView.

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

<!-- Single List Item Design -->
<RelativeLayout xmlns:android=""



There are two ways to populate the items of the string array to the Spinner. In the first way, you add the entries attribute of the Spinner in the activity_main.xml file. The value of the entries attribute is the string array.

Alternatively, you can programmatically populate the items of the string array to the Spinner. In the MainActivity class that hosts the Spinner, you write code as shown below.

public class MainActivity extends ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {

Spinner spinner=(Spinner)findViewById(;
String[] countries=getResources().getStringArray(R.array.array_countries);   
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner_layout,, countries);


Posted by: Dara | post date: 02-03-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.