Android Spinner Example Source Code

Android Spinner helps us to select an item from the drop down menu. In this post let us see an example on how to populate static values in the spinner drop down.

1. First create a new android project.
2. Under "res" folder you can see string.xml file. Add spinner title in this as illustrated in the below example.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">AndroidSpinner</string>
    <string name="spinner_title">Select</string>
</resources>

3. Now design a simple layout for spinner with a textview as shown below.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <!-- Text Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="Players:"
        android:layout_marginBottom="5dp"
    />

    <!-- Spinner Element -->
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/spinner_title"
    />
</LinearLayout>

4. Now let us see the key part, the Main Activity for Android Spinner below.

Here once the item is selected from the spinner drop down, the alert message toast gets displayed with the value what you have selected.

AndroidSpinnerActivity.java

package com.androidspinner;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class AndroidSpinnerActivity extends Activity implements OnItemSelectedListener{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Spinner Element
        Spinner spinner = (Spinner) findViewById(R.id.spinner);

        //On Spinner Item click listener
        spinner.setOnItemSelectedListener(this);

        // Spinner Values
        List<String> categories = new ArrayList<String>();
        categories.add("Sachin");
        categories.add("Dhoni");
        categories.add("Shewag");
        categories.add("Virat");
        categories.add("Raina");
        categories.add("Dravid");

        // Creating an adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);

        // Spinner Style as a List view with radio buttons
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(dataAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // On select spinner item
        String item = parent.getItemAtPosition(position).toString();

        // Displaying selected spinner item
        Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();

    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

5. Call the class name in the activity of your Manifest.xml file and just run it and enjoy playing with spinners and that's it.

Web Services Access Android Source Code

At first write a web service in java and deploy it in the tomcat Server. Let us see an example of a simple java web service below. First of all learn how to create a simple java web service.

package com.android.ws;
public class Hello {
 public String HelloAll(){
           return "Hello All";
        }
}

Now the web service part is ready and is deployed in the server. Next let us see on how to access and invoke this service from the android application using SOAP. Download ksoap2 library file from the below link and add it in the lib folder of your project.


MainActivity.java

We have to start a new thread to connect to the internet for android after versions 3.

import android.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
  
public class MainActivity extends Activity {
   
    private static final String SOAP_ACTION = "http://ws.android.com/HelloAll";
    private static final String METHOD_NAME = "HelloAll";
    private static final String NAMESPACE = "http://ws.android.com/";
    private static final String URL = "http://172.27.192.36:8080/webservicetest/services/HelloAll?wsdl";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
       
    Thread networkThread = new Thread() {
    @Override
    public void run() {
      try {
         SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);         
         SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
         envelope.setOutputSoapObject(request);
           
         HttpTransportSE ht = new HttpTransportSE(URL);
         ht.call(SOAP_ACTION, envelope);
         final  SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
         final String hello = response.toString();
  
         runOnUiThread (new Runnable(){ 
     public void run() {
         TextView result;
         result = (TextView)findViewById(R.id.textView1);
         result.setText(hello);
           }
       });
      }
     catch (Exception e) {
         e.printStackTrace();
     }
    }
  };
  networkThread.start();
  }
 }
}

Please find some important tips below to work great on this.

SOAP_ACTION is the "NAMESPACE/METHOD_NAME" mentioned in the above program.

METHOD_NAME is HelloAll in the WSDL File <wsdl:operation name="HelloAll">.

NAMESPACE is the targetNamespace in the WSDL File. Just add "/" in the end.

URL is the URL of the WSDL File. In the above code units you can see my ip address and kindly replace it with your own ip address. Never give it as localhost in the URL of the android code above. It does not take as localhost. Kindly give your own ip address. Make sure that the web service is also running on the same ip. If the web service part is deployed in some other server, then give the ip address of the corresponding server in the url part above and thats it.

Please find below the android manifest.xml file.

Just add uses permission for internet in the manifest file.

<manifest android:versioncode="1" android:versionname="1.0" package="com.android.ws" xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minsdkversion="15">
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:label="@string/app_name" android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">
                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
    </application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</uses-sdk></manifest>

Thats all for this and just start to rock. Have a nice day dear.
My Profile