Click here to Skip to main content
15,888,733 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi Friends,
Am not familiar with android development,and i came across a situation to cascade a dropdown based on the first spinner selection.i.e.,consider for an example in 1st spinner all states data are loaded from web service using db helper class while selecting the state name in the 1st spinner i need to populate the 2nd spinner based on the 1st spinner selected item's id(stateid not that spinner's selected item id) from db which means i need to select the stateid from the selected state and want to filter the districts based on the states.
State table creation:
SQL
CREATE TABLE States( StateID INTEGER , StateName VARCHAR)

District table creation:
SQL
CREATE TABLE Branches(_ID INTEGER PRIMAY KEY,DistrictName VARCHAR,StateID INTEGER)


In this I have used to load data for states by using arraylist and on spinner1.setOnItemSelectedListener function loaded the district values but the values are loading as per the position of the items in the states spinner instead of that i need to filter based on the stateid in the branch table.

This is the code for getting all states:
Java
public ArrayList<HashMap<String, String>> getStatesData() {
		ArrayList aList = new ArrayList();
		try {
			Log.e("getStatesData", "Started");
			String selectQuery = "SELECT * FROM States";
			SQLiteDatabase database = this.getWritableDatabase();
			Cursor cursor = database.rawQuery(selectQuery, null);
			if (cursor.moveToFirst()) {
				do {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put("StateID",
							cursor.getString(cursor.getColumnIndex("StateID")));
					map.put("StateName", cursor.getString(cursor
							.getColumnIndex("StateName")));
					aList.add(map);

				} while (cursor.moveToNext());
			}
			cursor.close();
			return aList;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("getStatesData", "Ended");
			return aList;
		}
	}



spinner1.setonitemselectedlistner event:

Java
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

          @Override
          public void onItemSelected(AdapterView<?> adapt, View v,
                  int pos, long id) {
              // TODO Auto-generated method stub

              long spinstate=spinner_state.getSelectedItemId();
      branch_values=sDBController.getStateselectidData(spinstate);
      branch_name_ary.clear();
      for (int i = 0; i < branch_values.size(); i++) {
          String name=branch_values.get(i).get("DistrictName");
          String id=branch_values.get(i).get("StateID");
          branch_name_ary.add(name);
          Log.e("branchesbystates", branch_name_ary.toString());
      }
      ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, branch_name_ary);
      spinnerArrayAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spinner_district.setAdapter(spinnerArrayAdapter1);
          }

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

          }
      });


Please suggest some solution to get the districts based on the stateid which may help to get an idea solve the issue.

Thanks in advance.
Posted
Updated 6-Apr-18 6:56am
v2

1 solution

I did something similar to this in a sales tax app some years ago. Trimming away the fat leaves something like:
// how the two tables are created
private static final String STATES_TABLE_CREATE =
    "CREATE TABLE " + STATES_TABLE + " ("
        + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
        + KEY_NAME + " TEXT);";

private static final String COUNTIES_TABLE_CREATE =
    "CREATE TABLE " + COUNTIES_TABLE + " ("
        + KEY_ID + " INTEGER REFERENCES " + STATES_TABLE + "(" + KEY_ID + "), "
        + KEY_NAME + " TEXT);";
...
class Info
{
    public long lStateId;
    public String sName;

    public Info( long lStateId, String sName )
    {
        this.lStateId = lStateId;
        this.sName    = sName;
    }

    @Override
    public String toString()
    {
        return sName;
    }
}
...
// populating the State spinner
ArrayList<Info> states = new ArrayList<Info>(50);
ArrayList<Info> counties = new ArrayList<Info>();

db = dbHelper.getReadableDatabase();
Cursor cursor = db.query(DatabaseHelper.STATES_TABLE, new String[]{DatabaseHelper.KEY_ID, DatabaseHelper.KEY_NAME}, null, null, null, null, DatabaseHelper.KEY_NAME);
if (cursor.moveToFirst())
{
    do
    {
        long lId = cursor.getLong(cursor.getColumnIndex(DatabaseHelper.KEY_ID));
        String sName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_NAME));

        states.add(new Info(lId, sName));

    } while (cursor.moveToNext());

    cursor.close();
}

db.close();
...
// respond to a selected State
@Override
public void onItemSelected( AdapterView<?> parent, View view, int position, long id )
{
    Info i = states.get(position);

    counties.clear();

    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = db.query(DatabaseHelper.COUNTIES_TABLE,
                             new String[]{DatabaseHelper.KEY_ID, DatabaseHelper.KEY_NAME},
                             DatabaseHelper.KEY_ID + " = ?",
                             new String[]{String.valueOf(i.lStateId)},
                             null,
                             null,
                             DatabaseHelper.KEY_NAME);

    if (cursor.moveToFirst())
    {
        do
        {
            long lId = cursor.getLong(cursor.getColumnIndex(DatabaseHelper.KEY_ID));
            String sName = cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_NAME));

            counties.add(new Info(lId, sName));

        } while (cursor.moveToNext());

        cursor.close();
    }

    if (counties.size() == 0)
        counties.add(new Info(-1, "No counties found for the selected state"));

    adapterCounties.notifyDataSetChanged();
    db.close();
}
This should get you close to what you are after.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900