Pete
Pete

Reputation: 784

How to check if a spinners item changed by user in android?

I am filtering something using spinners. I have two spinners, 1st with a list of States, 2nd with a list of colleges. When my program runs, I select a state in the 1st spinner, then my program filters the colleges in that state in the 2nd spinner. Now when I change the state in the 1st spinner, it does not filter it. I wanted to know how can select any state and then filter accordingly.

Spinner 1 Contain;

Select a state
[NY,NJ]

Spinner 2 Contain;

Select a College
[NYU, NYIT, NJIT] 

I wanna be able to select NY first and see NYU and then NYIT. Then I wanna select NJ and see NYIT.

Please give me some guideline.

Upvotes: 0

Views: 2718

Answers (3)

Sanket Shah
Sanket Shah

Reputation: 4382

spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
            {
                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) 
                {
                    String state= arg0.getSelectedItem().toString();

  // Here you can use selected string from spinner and set new value to another spinner with following code and enjoy doing it

                    ArrayAdapter<String> college= new ArrayAdapter<String>(Your_Context, your_layout, Your_Array);

                    spinner2.setAdapter(college);

                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) 
                {
                }
            });

Upvotes: 0

Kavin
Kavin

Reputation: 544

Implement onItemSelectedListener() for your first spinner and with the help of that you can get the selected value in your first spinner and according to that you populate your second spinner inside the first spinner's onItemSelected method.

spinner1.setOnItemSelectedListener(new OnItemSelectedListener() 
    {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) 
        {


            String selected = spinner1.getSelectedItem().toString();


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }
    });

You can also refer the following links to get an idea..

how to update spinner2 based on spinner1 choice

Based on a certain spinner selection populate another spinner

http://www.yogeshblogspot.com/android-spinner-example/

Upvotes: 0

Caleb Bramwell
Caleb Bramwell

Reputation: 1342

Use a database to store the values. Have one table for States and one Table for Colleges. In the colleges table have a column for storing the state Load the spinner from the States table and set an onClik listener. When the user clicks on State, search load the spinner from the Colleges table where column with State = selected State.

Below is a modifide class from http://www.androidhive.info/2012/06/android-populating-spinner-data-from-sqlite-database/

I would suggest going through his tutorial.

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

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    private static final String TABLE_STATES = "states";
    private static final String TABLE_COLLEGES = "colleges";

    // Labels Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_STATE = "state";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_STATES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_STATES_TABLE);
        String CREATE_COLLEGES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + KEY_STATE + "TEXT)";
        db.execSQL(CREATE_COLLEGES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_STATES);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_COLLEGES);

        // Create tables again
        onCreate(db);
    }

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllStates(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_STATES;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }

    public List<String> getCollegs(String state){
            List<String> labels = new ArrayList<String>();

            // Select All Query
            String selectQuery = "SELECT  * FROM " + TABLE_COLLEGES + " WHERE " + KEY_STATE " EQUALS " + state;

            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do {
                    labels.add(cursor.getString(1));
                } while (cursor.moveToNext());
            }

            // closing connection
            cursor.close();
            db.close();

            // returning lables
            return labels;
        }
    }

Upvotes: 1

Related Questions