title: Populating Spinner using ArrayList in Android
body: <p>I have an activity in which I have to parse an XML and populate a Spinner using the parsed data.</p>
  
  <p>I am done with parsing the XML. This is the method:</p>
  
  <pre><code>void parse_ExamList()
                      {
  
                          ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
                          XMLParser parser = new XMLParser();
                          //String xml = parser.getXmlFromUrl(URL); // getting XML
                          Document doc = parser.getDomElement(xmlContent); // getting DOM element
  
                          //count_questions=2;
  
                          NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
                          // looping through all item nodes &lt;item&gt;
                          for ( int i = 0; i &lt; nl.getLength();i++) {
  
  
  //                      while(counter&lt; nl.getLength())
  //                      {
                              // creating new HashMap
                              HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
  
                              Element e = (Element) nl.item(i);
                              // adding each child node to HashMap key =&gt; value
                              //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
                              map.put(KEY_SETID, parser.getValue(e, KEY_SETID));
                              map.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME));
                              //Log.i("Set ID: ", parser.getValue(e, KEY_SETID));
                              //Log.i("Set Name: ", parser.getValue(e, KEY_SETNAME));
  
                              menuItems.add(map);
                          }
  
  
                      }
  </code></pre>
  
  <p>If you notice you can see that <strong>KEY_SETID</strong> and <strong>KEY_SETNAME</strong> to the arraylist. I have to populate the spinner with the <strong>KEY_SETNAME</strong> and the <strong>KEY_SETID</strong> will not be shown in the spinner. But if the item is clicked then the id corresponding to the name should be acquired in order to send to the server.</p>
  
  <p>I have a method to populate a spinner, like this:</p>
  
  <pre><code>// add items into exam list spinner dynamically
                      public void addItemsOnExamListSpinner()
                      {
                          List&lt;String&gt; list = new ArrayList&lt;String&gt;();
                          list.add("Speed Test 150(min) PO Set-01");
  
                          ArrayAdapter&lt;String&gt; dataAdapter = new ArrayAdapter&lt;String&gt;(this,
                          android.R.layout.simple_spinner_item, list);
                          dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                          exam_list_spinner.setAdapter(dataAdapter);
                      }
  </code></pre>
  
  <p><strong>How should I populate the spinner with the ArrayList that is obtained while parsing the XML?</strong></p>
  
  <p>This is the <strong>full activity</strong>:</p>
  
  <pre><code>public class SpeedTestExamNameActivity extends Activity {
  
      Spinner exam_list_spinner;
      Button  detailsBtn;
      TextView showUser;
      String full_name;
  
      //variables to get response from server
      String responseBody;
  
      //variables required for parsing the XML
      String xmlContent=null;
  
   // XML node keys
      static final String KEY_EXAMSET = "ExamSet"; // parent node
      static final String KEY_SETID = "SetId";
      static final String KEY_SETNAME = "SetName";
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_speed_test_exam_name);
  
          //checking internet connectivity to download list
          isOnline_downloadList();
  
          //Showing user full name after login
          full_name=getFromPreference("user_name");
          //textview to show user name
          showUser=(TextView)findViewById(R.id.speed_username_textView);
          showUser.setText("Welcome, "+full_name);
          //spinner
          exam_list_spinner = (Spinner) findViewById(R.id.speed_examlist_spinner);
          //adding items to spinners
          addItemsOnExamListSpinner();
  
          // onclick details button
          detailsBtn = (Button) findViewById(R.id.speed_exam_details_button);
          detailsBtn.setOnClickListener(new View.OnClickListener() {
  
                      @Override
                      public void onClick(View v) {
  
                          Toast.makeText(SpeedTestExamNameActivity.this,                      
                                  "Exam List Spinner: "+ String.valueOf(exam_list_spinner.getSelectedItem()),
                                  Toast.LENGTH_SHORT).show();
  
                          Intent intent = new Intent(SpeedTestExamNameActivity.this, SpeedTestActivity.class);
                          SpeedTestExamNameActivity.this.startActivity(intent);
                      }
                    });
      }
  
  
  
      //getting content from preferences
          public String getFromPreference(String variable_name)
          {
              String preference_return;
              SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
              preference_return = preferences.getString(variable_name,"");
  
             return preference_return;
          }
  
  
          //check connection
          public boolean isOnline_downloadList() {
              ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo netInfo = cm.getActiveNetworkInfo();
              if (netInfo != null &amp;&amp; netInfo.isConnectedOrConnecting()) {
  
                  //sending request for login
                  new MyAsyncTask().execute(getFromPreference("student_code"));
  
  
  
                  return true;
              }
  
            //alert box to show internet connection error
              AlertDialog.Builder Internet_Alert = new AlertDialog.Builder(SpeedTestExamNameActivity.this);
              // set title
              Internet_Alert.setCancelable(false);
              Internet_Alert.setTitle("Attention!");
              Internet_Alert.setMessage("This application requires internet connectivity, no internet connection detected");
              Internet_Alert.setPositiveButton("Quit", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface arg0, int arg1) 
                  {
                      Intent intent = new Intent(Intent.ACTION_MAIN);
                      intent.addCategory(Intent.CATEGORY_HOME);
                      intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                      startActivity(intent);
                      onQuitPressed(); 
                  }
              });
  
              Internet_Alert.create().show();
              return false;
          }
  
          //to remove application from task manager
          public void onQuitPressed() {
  
              int pid = android.os.Process.myPid();
              android.os.Process.killProcess(pid);
          }
  
  
  
          //===================================================================================================================================
          //sending student code to server to get exam list
          //===================================================================================================================================
          private class MyAsyncTask extends AsyncTask&lt;String, Integer, Double&gt;{
  
  
              @Override
              protected Double doInBackground(String... params) {
                  // TODO Auto-generated method stub
                  postData(params[0]);
                  return null;
              }
  
              protected void onPostExecute(Double result){
  
                  //Toast.makeText(getApplicationContext(), responseBody, Toast.LENGTH_LONG).show();
                  //Log.i("response: ", responseBody);
                  //processResponce(responseBody);
                  //going to next activity
                  xmlContent=responseBody;
                  parse_ExamList();
              }
  
              protected void onProgressUpdate(Integer... progress){
  
              }
  
              public void postData(String student_code) {
                  // Create a new HttpClient and Post Header
                  HttpClient httpclient = new DefaultHttpClient();
                  //HttpPost httppost = new HttpPost("http://icaerp.com/AndroidDataService/dataServiceAndroid.asmx/login");
  
                  SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(SpeedTestExamNameActivity.this);
                    final String url_first = preferences.getString("URLFirstPart","");
                  HttpPost httppost = new HttpPost(url_first+"ExamList");
  
                  try {
                      // Data that I am sending
                      List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;();
                      nameValuePairs.add(new BasicNameValuePair("StudentCode", student_code));
                      //nameValuePairs.add(new BasicNameValuePair("Password", passwrd));
                      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  
                      // Execute HTTP Post Request
                      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                      HttpResponse response = httpclient.execute(httppost);
                      responseBody = EntityUtils.toString(response.getEntity());
  
                      Log.d("result", responseBody);
                  } 
                  catch (Throwable t ) {
                      //Toast.makeText( getApplicationContext(),""+t,Toast.LENGTH_LONG).show();
                      Log.d("Error Time of Login",t+"");
                  } 
              }
          }
          //===================================================================================================================================
          //END sending EmailAddress and Password to server 
          //===================================================================================================================================
  
          // function to populate SPINNER with exam list from xml
                      void parse_ExamList()
                      {
  
                          ArrayList&lt;HashMap&lt;String, String&gt;&gt; menuItems = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;();
  
                          XMLParser parser = new XMLParser();
                          //String xml = parser.getXmlFromUrl(URL); // getting XML
                          Document doc = parser.getDomElement(xmlContent); // getting DOM element
  
                          //count_questions=2;
  
                          NodeList nl = doc.getElementsByTagName(KEY_EXAMSET);
                          // looping through all item nodes &lt;item&gt;
                          for ( int i = 0; i &lt; nl.getLength();i++) {
  
  
  //                      while(counter&lt; nl.getLength())
  //                      {
                              // creating new HashMap
                              HashMap&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
  
                              Element e = (Element) nl.item(i);
                              // adding each child node to HashMap key =&gt; value
                              //map.put(KEY_EXAMSET, parser.getValue(e, KEY_EXAMSET));
                              map.put(KEY_SETID, parser.getValue(e, KEY_SETID));
                              map.put(KEY_SETNAME, parser.getValue(e, KEY_SETNAME));
                              //Log.i("Set ID: ", parser.getValue(e, KEY_SETID));
                              //Log.i("Set Name: ", parser.getValue(e, KEY_SETNAME));
  
                              menuItems.add(map);
                          }
  
  
                      }
  
                      // add items into exam list spinner dynamically
                      public void addItemsOnExamListSpinner()
                      {
                          List&lt;String&gt; list = new ArrayList&lt;String&gt;();
                          list.add("Speed Test 150(min) PO Set-01");
  
                          ArrayAdapter&lt;String&gt; dataAdapter = new ArrayAdapter&lt;String&gt;(this,
                          android.R.layout.simple_spinner_item, list);
                          dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                          exam_list_spinner.setAdapter(dataAdapter);
                      }
  
  
  }
  </code></pre>
  
  <p>This is the <strong>layout file</strong>:</p>
  
  <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:paddingBottom="@dimen/activity_vertical_margin"
      android:paddingLeft="@dimen/activity_horizontal_margin"
      android:paddingRight="@dimen/activity_horizontal_margin"
      android:paddingTop="@dimen/activity_vertical_margin"
      tools:context=".SpeedTestExamNameActivity" &gt;
  
      &lt;TextView
          android:id="@+id/textView1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentTop="true"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="30dp"
          android:text="@string/speed_choose_exam"
          android:textAppearance="?android:attr/textAppearanceLarge" /&gt;
  
      &lt;Spinner
          android:id="@+id/speed_examlist_spinner"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/textView1"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="68dp" /&gt;
  
      &lt;Button
          android:id="@+id/speed_exam_details_button"
          android:layout_width="95dp"
          android:layout_height="wrap_content"
          android:layout_below="@+id/speed_examlist_spinner"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="36dp"
          android:text="@string/details" /&gt;
  
      &lt;TextView
          android:id="@+id/speed_username_textView"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentRight="true"
          android:layout_alignParentTop="true"
          android:text="Name Title"
          android:textAppearance="?android:attr/textAppearanceSmall" /&gt;
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p><strong>What should I do to populate the Spinner from the Arraylist returned by the XML parsing method?</strong></p>