Q:

How to display string item in spinner and store it as a integer value in database

Here in my android project i have used Four spinners..and i am saving the selected spinner item in the database on click of a button..here the spinner items are saving as a string in database..Now what i want is, i have to save assigned numeric value for the spinner item in a database.
For example,if i select Mr in 1st spinner it has to save as 1 in database.
            if i select Ms,it has to save as 2 in database.
and if i select India in Country,it has to save as 91 in database..
Can anyone please tell me how to achieve this one..
Any help would be much appreciated..Thanks in Advance..!!
MainActivity
package com.example.server;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings({ "deprecation", "unused" })
public class MainActivity extends Activity {

    private Spinner spin;
    private Spinner spin1;
    private Spinner spin2;
    private Spinner spin3;
    private EditText editTextFname;
    private EditText editTextLname;
    private EditText editTextMobile;
    private EditText editTextPin;
    //private EditText editTextPin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spin = (Spinner)findViewById(R.id.spinner1);
        spin1 = (Spinner)findViewById(R.id.spinner2);
        spin2 = (Spinner)findViewById(R.id.spinner3);
        spin3 = (Spinner)findViewById(R.id.spinner4);
        editTextFname = (EditText) findViewById(R.id.editTextFname);
        editTextLname = (EditText) findViewById(R.id.editTextLname);
        editTextMobile = (EditText) findViewById(R.id.editTextMobile);
        editTextPin = (EditText) findViewById(R.id.editTextPin);

        ArrayAdapter<CharSequence> spinner = ArrayAdapter.createFromResource(this, R.array.salutation_arrays, android.R.layout.simple_spinner_item);
        spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(spinner);

        ArrayAdapter<CharSequence> spinner1 = ArrayAdapter.createFromResource(this, R.array.country_arrays, android.R.layout.simple_spinner_item);
        spinner1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin1.setAdapter(spinner1);

        ArrayAdapter<CharSequence> spinner2 = ArrayAdapter.createFromResource(this, R.array.state_arrays, android.R.layout.simple_spinner_item);
        spinner2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin2.setAdapter(spinner2);

        ArrayAdapter<CharSequence> spinner3 = ArrayAdapter.createFromResource(this, R.array.city_arrays, android.R.layout.simple_spinner_item);
        spinner3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin3.setAdapter(spinner3);

    }

    public void Register(View view){

        String salutation = spin.getSelectedItem().toString();
        String fname = editTextFname.getText().toString();
        String lname = editTextLname.getText().toString();
        String mobile = editTextMobile.getText().toString();
        String country = spin1.getSelectedItem().toString();
        String state = spin2.getSelectedItem().toString();
        String city = spin3.getSelectedItem().toString();
        String pin = editTextPin.getText().toString();

        insertToDatabase(salutation,fname,lname,mobile,country,state,city,pin);

        /*Uri uri = Uri.parse("http://oursite/insert-db.php"); // opens google site if insert button is pressed.
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        startActivity(intent);*/
    }

    private void insertToDatabase(String salutation, String fname, String lname,String mobile, String country, String state, String city, String pin){
        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @SuppressWarnings({ "unused", "deprecation" })
            @Override
            protected String doInBackground(String... params) {
                @SuppressWarnings("unused")
                String paramSalutation = params[0];
                String paramFname = params[1];
                String paramLname = params[2];
                String paramMobile = params[3];
                String paramCountry = params[4];
                String paramState = params[5];
                String paramCity = params[6];
                String paramPin = params[7];

                //InputStream is = null;

                String salutation = spin.getSelectedItem().toString();
                String fname = editTextFname.getText().toString();
                String lname = editTextLname.getText().toString();
                String mobile = editTextMobile.getText().toString();
                String country = spin1.getSelectedItem().toString();
                String state = spin2.getSelectedItem().toString();
                String city = spin3.getSelectedItem().toString();
                String pin = editTextPin.getText().toString();

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("salutation", salutation));
                nameValuePairs.add(new BasicNameValuePair("fname", fname));
                nameValuePairs.add(new BasicNameValuePair("lname", lname));
                nameValuePairs.add(new BasicNameValuePair("mobile", mobile));
                nameValuePairs.add(new BasicNameValuePair("country", country));
                nameValuePairs.add(new BasicNameValuePair("state", state));
                nameValuePairs.add(new BasicNameValuePair("city", city));
                nameValuePairs.add(new BasicNameValuePair("pin", pin));

                try {
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(
                            "http://oursite/insert1-db.php");
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpClient.execute(httpPost);

                    HttpEntity entity = response.getEntity();

                    //is = entity.getContent();

                } catch (ClientProtocolException e) {

                } catch (IOException e) {

                }
                return "success";
            }

            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);

                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
                TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
                textViewResult.setText("Inserted");
            }
        }
        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
        sendPostReqAsyncTask.execute(salutation,fname,lname,mobile,country,state,city,pin);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

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

    <string name="app_name">Server</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="salutation_prompt">Salutation</string>
     <string-array name="salutation_arrays">

        <item>Mr</item>
        <item>Ms</item>

    </string-array>

    <string name="country_prompt">Choose a country</string>
    <string-array name="country_arrays">

         <item>India</item><!--here i need to save 91 if india is selected.-->
          <item>Srilanka</item><!--here i need to save 94 if srilanka is selected.-->
        <item>Malaysia</item><!--here i need to save 60 if malaysia is selected.-->
          <item>Australia</item>
        <item>USA</item>

    </string-array>

    <string name="state_prompt">Select a State</string>
     <string-array name="state_arrays">

        <item>Karnataka</item>

    </string-array>

    <string name="city_prompt">Select City</string>
     <string-array name="city_arrays">

        <item>Bangalore</item>

    </string-array>

</resources>

Logcat
01-11 16:54:16.046: E/AndroidRuntime(27447): FATAL EXCEPTION: main
01-11 16:54:16.046: E/AndroidRuntime(27447): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.server/com.example.server.MainActivity}: java.lang.NullPointerException
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread.access$700(ActivityThread.java:143)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.os.Looper.loop(Looper.java:137)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread.main(ActivityThread.java:4960)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at java.lang.reflect.Method.invokeNative(Native Method)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at java.lang.reflect.Method.invoke(Method.java:511)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at dalvik.system.NativeStart.main(Native Method)
01-11 16:54:16.046: E/AndroidRuntime(27447): Caused by: java.lang.NullPointerException
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.content.res.AssetManager.getResourceTextArray(AssetManager.java:214)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.content.res.Resources.getTextArray(Resources.java:1274)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.widget.ArrayAdapter.createFromResource(ArrayAdapter.java:431)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at com.example.server.MainActivity.onCreate(MainActivity.java:100)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.Activity.performCreate(Activity.java:5203)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
01-11 16:54:16.046: E/AndroidRuntime(27447):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
01-11 16:54:16.046: E/AndroidRuntime(27447):    ... 11 more

A:

Define two arrays:

private static final int[] AreaCode = new int[]{90, 110, 120}; // array to save area code
private static final String[] Area = new String[]{"Area 90","Area 110","Area 120"}; // array to show location

//Use adapter to show values in spinner
ArrayAdapter<String> adpt_area = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_dropdown_item, Area);
spn_area.setAdapter(adpt_area);

// get selected item position
int selectedPosition = spn_area.getSelectedItemPosition();
// get area code based on value selected in spinner
String areaCodeByPosition = String.valueOf(AreaCode[selectedPosition]);
// check log value
Log.d("%%%", "Area selected:  " + selectedPosition + " *** Relative code: "+areaCodeByPosition);

