Search code examples
androidweb-servicessqliteadtandroid-spinner

populating spinner based on the previous spinner selection in android


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: CREATE TABLE States( StateID INTEGER , StateName VARCHAR) District table creation: 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:

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:

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.


Solution

  • if i were you, i would create a State like so

    public class State {
    private String id;
    private String name;
    
    public State(String id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public String getId() {
        return id;
    }
    
    public void setId(String id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return name;
    }
    

    }

    and the getStatesDate method would be like this:

    public List<State> getStatesData()
    {
        List<State> states = new ArrayList<State>();
        try {
            Log.e("getStatesData", "Started");
            String selectQuery = "SELECT * FROM States";
            SQLiteDatabase database = this.getWritableDatabase();
            Cursor cursor = database.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
                do {
                    String stateId = cursor.getString(cursor.getColumnIndex("StateID"));
                    String stateName = cursor.getString(cursor.getColumnIndex("StateName"));
                    states.add(new State(stateId, stateName));
    
                } while (cursor.moveToNext());
            }
            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("getStatesData", "Ended");
        }
    
        return states;
    }
    

    and the spinner1 onClicklistener will also be like this:

    spinner1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                State state = (State) spinner1.getSelectedItem();
    
                String stateId = state.getId();
                String stateName = state.getName();
    
                //you are very assured that the id matches the name selected and you can proceed from there
            }
        });
    

    I hope it helps. Cheers